简体   繁体   中英

Adding to integer array base address C?

int main()
{
    int a[] = {1,2,3,4,5};
    printf("Base Address of array = %p\n",a);
    printf("Address1 = %p \t Address2 = %p\n",a+1,&a+1);
    return 0;
}

In the print both the case "a" represents the base address of array,but the first one increment 4 bytes and the second by 20 bytes. Any specific reason ?

Output:

Base Address of array 0x7fff2059b240                                                                                                                        
Address1 = 0x7fff2059b244         Address2 = 0x7fff2059b254 

Two concepts:

  1. Pointer arithmetic is based on the size of the pointed-to type. In other words, if you have a pointer to type T , then adding 1 to that pointer will give you the address of the next object of type T .

  2. Except when it is the operand of the sizeof or unary & operators, an expression of type "N-element array of T " will be converted ("decay") to an expression of type "pointer to T ", and the value of the expression will be the address of the first element of the array.

You declared a as a 5-element array of int . Assuming 4-byte int , the array occupies 20 bytes.

The expression a "decays" to type int * , so adding 1 to it gives you the address of the next int object following a (IOW, it's the same as &a[1] ).

The expression &a has type int (*)[5] (pointer to 5-element array of int ), so adding 1 to it gives you the address of the next 5-element array of int .

The size of what &a points to is 20 bytes (the whole array: 4 bytes x 5 elements), while the size of what a points to is 4 bytes (a single int ). The fact that they are both at the same address is irrelevant; they are different ways of interpreting what is at that address.

When you increment a+1 a is actually a pointer to int so its incremented 4 bytes, that is the size of int. But when you do &a , it becomes address of an array of 5 ints, so if you increment that, you will skip size of array of 5 ints.

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