Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do "a+1" and "&a+1" give different results when "a" is an int array?

Tags:

c

int main()
{
    int a[]={1,2,3,4,5,6,7,8,9,0};

    printf("a = %u , &a = %u\n",a,&a);
    printf("a+1 = %u , &a+1 = %u\n",a+1,&a+1);
}

how a and &a are internally interpreted?

like image 215
shraddha Avatar asked Jun 07 '10 12:06

shraddha


2 Answers

Both statements print out addresses and are probably meant to explain pointer arithmetic.

a and &a are NOT the same, they have different types, but hold the same memory address.

&a is of type int (*)[10] (which acts like a pointer to an array)
a is of type int [10] (which acts like a pointer to a single element)

So when you add 1 keep those types in mind. The pointer will be offset by the size of the type that the address contains. a+1 offsets by the size of int, i.e. to the second element in the array. &a+1 offsets completely past the whole array.

like image 129
Brian R. Bondy Avatar answered Oct 21 '22 02:10

Brian R. Bondy


Well, a is the address of the first element of the array, and &a is the address of the array, but obviously they both have the same address.

However when you add (or subtract) a number from a pointer the compiler takes the size of the data into consideration thus in your case (assuming the size of int is 4 bytes) a+1 will be bigger than a by 4 because you move the pointer one integer ahead, but &a+1 would be bigger by 40 because you more the pointer one ARRAY OF 10 INTEGERS ahead.

like image 27
Bob Avatar answered Oct 21 '22 02:10

Bob