I'm trying to understand how pointer arithmetic works in C. Say if I have two arrays, one static and the other dynamic like so,
int a[10];
int * b = malloc(sizeof(int) * 10);
And lets assume each array has been initialized so that they both store numbers from 0 to 9 in order (well in the case for b, it stores the address to an array of numbers from 0 to 9 in order).
If we want to access the value 9 in array a using pointer arithmetic we can simply write *(a + 9).
Similarly if we want to access the value 9 in array b, we can simply write *(b + 9).
However what confuses it me is how the computer is able to know when to dereference a variable. With the case for a, the computer treats the name as an address of the array a. However with b, it seems that the computer reads the address of b and also dereferences it additionally in order to get the base address of the array pointed by b.
Could someone please explain?
(Edit: specifically my confusion is related to how the names of both arrays are treated by the computer. For *(a + 9), the name a is read by the computer as an address of array a itself and added to (9 * 4). While for *(b + 9), b is instead read as the address stored in variable b.)
ais a constant. Like12. A constant address. Sort of. But still an address. So*(b+9)is exactly the same arithmetic as*(a+9). The difference is the same as betweenint b=12;and then comparingb+5and12+5. Sure,bis a variable and12is not. Yet, it is the same arithmetic. So, same for your pointer. Surebis a variable (containing an address), andais not. Still, same arithmetic. (Switchedaandbin previous comment. And realized 1 minutes too late to edit)ais not a variable. There is no address ofa. It is stored nowhere.a[0],a[1], ... are stored somewhere in the memory. But nota.a, C treats the symbolaas designating the array object it is associated with. Just like in the context ofb, it always treats the symbolbas designating the pointer object it is associated with. There just are special rules for how arrays are handled, as your answers and other comments explain in more detail. There are special rules for a variety of other data types, too, though those for arrays are somewhat unusual.