0
#include <stdio.h>

int func(int *p , int n)
{
    for(int i = 0 ; i < n ; i ++)
    {
         printf("%d\n", *(p + i));
         *(p + i) +=1;
         p = ++p;
         printf("%d\n", p);


    }
}
int main()
{
   int arr[5] = {1,2,3,4,5};
   func(arr, 5);
    for(int i = 0 ; i < 5 ; i ++)
    {
        printf("%d\t %d\n", arr[i], &arr[i]);

    }
}

Output on the console:

1
-2128162268
3
-2128162264
5
-2128162260
0
-2128162256
4195824
-2128162252
2    -2128162272
2    -2128162268
4    -2128162264
4    -2128162260
6    -2128162256

Why does *(p + i) +=1; not increment as expected? Here address stored in p changes everytime.

Ex - if we have an array of 4 integers -

 p = &a[0];
    &a[0] = 200
then, p + 1 = 200 + 4
      p + 2 = 200 + 8

In , the above program the address stored in p is not base address of array once it's incremented.

Can anyone please explain?? Where the thing's are going wrong?

Edit : Solved, for future reference. This is how the program behaves!

i = 0
*(p + 0) = *(-2128162272 + 0) = *(-2128162272) = Value to be incremented at &a[0]
p ++
p = -2128162268

i = 1
*(p + 1) = *(-2128162268 + 4) = *(-2128162264) = Value to be incremented at &a[3]
p = -2128162264

i = 2
*(p + 2) = *(-2128162264 + 4 * 2) = *(-2128162256) = Value to be incremented at &a[5]
p = -2128162260

i = 3
*(p + 3) = *(-2128162260 + 4 * 3) = *(-2128162252) = Value to be incremented at address -2128162252
p =  -2128162256

0 Answers0