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));
}
This is because of the pointer type to which the pointer arithmetic operation ptr+i is applied:
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.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