I know this has been hashed over a number of time, but I have come across a case today that shook my understanding of the pointer math/ array index.
As I have allways understood it, &mybuff[10] and (&mybuff+10) are equivilent ways of referancing the same memory.
However I spent the morning fighting a case where:
memcpy(&mybuff+10,&in,8);
overflowed the buffer, when compiled with optimization on and worked just fine when compiled for debugging.
While athe same time,
memcpy(&mybuff[10],&in,8);
worked just fine in both cases.
Many thanks for any ideas or pointers.
Pointer arithmetic is actually about 30% faster than using array indexes.
So expression *(p+1) has type int. Since p[1] abbreviates *(p+1), p[1] has type int. It is the item in array p at index 1. An array is a pointer, and you can store that pointer into any pointer variable of the correct type.
The main difference between Array and Pointers is the fixed size of the memory block. When Arrays are created the fixed size of the memory block is allocated. But with Pointers the memory is dynamically allocated.
Why ? pointers because it is direct memory access followed by dereferencing array - add current index to base address then dereferencing.
&mybuff[10]
is equivalent to &mybuff[0] + 10
which is equivalent to mybuff + 10
Array indexing is defined in terms of pointer arithmetic. p[i]
means *(p+i)
(I'm ignoring the need for extra parentheses in case p
or i
is a more complex expression), where p
is a pointer value and i
is an integer value.
Trivia: Since addition, even pointer+integer addition, is commutative, p[i]
can also be written as i[p]
. Yes, 4["Hello"] == 'o'
. For the sake of anyone who reads your code in the future, please do not make use of this knowledge.
An excellent reference on the relationship between arrays and pointer in C (and C++, where the rules are nearly identical) is section 6 of the comp.lang.c FAQ. (I could have linked directly to section 6, but I like to encourage people to browse it; the whole thing is worth reading.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With