Inconsistency in using pointer to an array and address of an array directly

前端 未结 4 1603
执念已碎
执念已碎 2020-12-06 07:08

This code sample prints the array correctly.

int b[2] = {1, 2};
int *c = &b;
int  i, j,k = 0;
for (i = 0;i < 2; i++) {
    printf(\"%d \", *(c+i));
}
         


        
4条回答
  •  失恋的感觉
    2020-12-06 07:16

    This is because of the pointer type to which the pointer arithmetic operation ptr+i is applied:

    • In the first case, you add i to a pointer to int, which is the same as indexing an array. Since the pointer to an array is the same as the pointer to its first element, the code works.
    • In the second case, you add i to a pointer to an array of two ints. Therefore, the addition puts you beyond the allocated memory, causing undefined behavior.

    Here is a quick illustration of this point:

    int b[2] = {1,2};
    printf("%p\n%p\n%p\n", (void*)&b, (void*)(&b+1), (void*)(&b+2));
    

    On a system with 32-bit ints this prints addresses separated by eight bytes - the size of int[2]:

    0xbfbd2e58
    0xbfbd2e60
    0xbfbd2e68
    

提交回复
热议问题