简体   繁体   中英

C program address increment of array and array name

int arr[10]={1,2,3,4,5,6,7,8,9,10};
printf("%p,%p\n", arr, &arr);
printf("%p,%p\n", arr+1, &arr+1);
return 0;

For this code, GCC compiler return

0xbfe41348,0xbfe41348
0xbfe4134c,0xbfe41370

The first line is clear, no problem. But the second line makes me confused. The first address moves to the next int , so it is 4 bytes after arr , clear. However, for &arr+1 I thought it will point to the end of the whole array arr[10] , so it should add 4*10 to the address. Do I misunderstand something?

The type of &arr is 'pointer to array of 10 int '. Therefore, when you add one to it ( &arr+1 ), it moves to the start of the next array of 10 int , which is 40 bytes beyond the start of &arr .

What you think is right and it is done that way only.

Since &arr => 0xbfe41348 and

0xbfe41348 + 0x28 ( 4*10 in decimal) = 0xbfe41370

I think you got confused due to addition of decimal to a hexadecimal number.

&arr+1 does, in fact, add 40 to the base address of the array arr but it's not obvious since the addresses are in hexadecimal or base 16, not decimal.

Now, for what it's worth, I'll add some explanation of each statement to make things clear.

int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

The above statement defines arr to be of type int[10] , ie, an array of 10 integers. It then initializes arr with an array initializer list.

printf("%p,%p\n", arr, &arr);

In the above statement arr decays (evaluates or implicitly converted) to a pointer to its first element. Therefore its type is int * . &arr evaluates to a pointer to arr . Type of arr is int[10] . Therefore, type of &arr is int (*)[10] , ie, a pointer to an array of 10 integers. Parentheses are used because array subscript operator [] has higher precedence than * operator. So without parentheses int *[10] means an array of 10 pointers to integers. This is one of the cases where an array does not decay into a pointer to its first element.

Please note that both arr and &arr evaluate to the same value, ie, the base address of the array in the above printf statement but their types are different and they have different pointer arithmetic. This shows up in the following statement -

printf("%p,%p\n", arr+1, &arr+1);

arr+1 points to the next element. Here element type is int . Therefore arr+1 evaluates to

arr + (1 * sizeof(int)) 

&arr + 1 also points to the next element but here the element type is int[10] - an array of 10 integers . Therefore &arr + 1 evaluates to

arr + (1 * sizeof(int[10]))
arr+1

Here arr is base pointer to integer array so results in incremented by sizeof(int)

&arr+1

Here &arr results in address of array so result is incremented by array size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM