Aryan poonacha Aryan poonacha - 2 years ago 70
C Question

How can elements of an array be accessed by adding numbers to the array 'name', i.e the constant pointer that stores the first element's address?

In C, I was taught that we can access the elements of an array using pointers by incrementing the address by the memory size of data type of the array. So for an array A storing integers,

int *ptr = &A[0];
for(int i = 0; i<3; i++)
printf("%p\n", *ptr)
ptr++ // here it's +4 cause int

Would print all 3 values of array A. However, since the name of the array is a constant pointer that has the address of the array's first element, I also saw this code:

<information on site>

double *p;
double balance[10];

p = balance;

It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].


But how? If I add +4 to the address stored in pointer balance, if balance[] is an int array, then it's the equivalent of incrementing it, then that would make it move from pointing balance[1] to balance[2], not to balance[4]. So dereferencing (*(balance+4)) would give the value of balance[1], not [4], right? Please explain.

Answer Source

the compiler knows you are pointing to a double array so when using (*(balance+4)) the compiler actually makes it to be (double)(*(((char*) balance) + 4*sizeof(pointee)))

explanation: when using pointer of a type A then the statement A* p = SOME_ADDRESS; p++ makes p move sizeof(A) bytes forward, meaning it has gone from address X to address X+sizeof(A) (in bytes)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download