Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

want to understand a C array behaviour

Please see the following code snippet:

int main()
{

    int arr[] = { 0,3 , 4,28,1198};
    for(int i=0;i<5;i++)
    printf("\n arr[i] %u \n" , arr+i);
    printf("\n *******************\n");
    printf("%u ", &arr+1);

    return 1;

}

When it is run, it outputs:

arr[i] 3219650892 

 arr[i] 3219650896 

 arr[i] 3219650900 

 arr[i] 3219650904 

 arr[i] 3219650908 

 *******************
3219650912 

It seems that it is showing me the last element's address added with 1 more integer which seems to be strange. I feel it should have given me address of second element.

Can you help me understand this behavior?

like image 395
MAG Avatar asked Apr 21 '13 16:04

MAG


2 Answers

To understand this, compare the meaning of arr with &arr.

arr is the name for the array. C has a rule that an array expression is converted to a pointer to the first element (except in some particular situations that do not apply here). So arr is converted to &arr[0], which is the address of the first element. This is a pointer to int, so, when you add 1 to it, you get a pointer to the next int. Thus, successive increments to this pointer increment through elements of the array.

In contrast, &arr is a pointer to the array.* The starting address of the array and the starting address of the first element are the same, but they have different types. The type of &arr is ”pointer to array of five int”. When you add 1 to this, you get a pointer to the next array of five int. That is, the address is incremented by the size of an entire array of five int.

Incidentally, it is inappropriate to use a %u specifier to print addresses. You should use %p and convert the addresses to void *, such as:

printf("%p ", (void *) (&arr+1));

Footnote

* This is one of those special situations: When an array is used with &, the conversion is not done. In &arr, arr is the array, not a pointer, and &arr is its address.

like image 138
Eric Postpischil Avatar answered Oct 11 '22 04:10

Eric Postpischil


&arr+1

&arr is a pointer to the array arr, so &arr + 1 points at the address of the last element of arr array + 1 element. That is arr last element address is &arr[4] so &arr + 1 is the same address as &arr[5] (but the type is different).

like image 20
ouah Avatar answered Oct 11 '22 04:10

ouah