I’ve just read this that by pointing a pointer to the first array member, you can cycle through by adding to the pointer.
char my_array[] = "I am an array of chars";
char *my_pointer = my_array;
printf("%c\n", *my_pointer);
my_pointer++;
printf("%c", *my_pointer);
I guess this implies array members are always stored sequentially, and the space allocated is always reserved and an array’s size can not be extended (because after the length it may contain other things in memory)?
Why does this work exactly? When accessing an array using a subscript, like my_array[5], will C only know where the array starts (i.e. my_array[0]), and have to increase an internal pointer by 5 to return it?
I apologize if this seems obvious, but I’ve spent my life in high level languages and C is very interesting to me.
Putting aside the problems with your code, yes, arrays are contiguous elements.
What happens with the second line of the code snippet below:
is thus:
10is multiplied by the size of theintto get 70 (in this example, we assume a 7-byteint).iptr(unscaled) and the (7-byte) value is extracted from that location.This scaling is an important feature. You won’t see it when you’re working with
chararrays but the values&(iptr[0])and&(iptr[1])will be separated by the size of anint, not achar(7 in our example case above).When you add 1 to a pointer, that doesn’t actually add 1, it adds the size of the underlying data type. So that:
won’t give you an address corresponding to the second byte of that memory, it will actually give you the address of the second
int(the seventh byte).To that end,
iptr[3]is exactly equivalent to*(i+3)in that they both give you element number three, even though it’s made up of bytes from offset 21 through 27 inclusive.Pre-emptive strike, just in case: keep in mind that a byte in ISO C is not necessarily 8 bits. ISO uses the term
octetfor that. A byte is the size of achar.