Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer math vs. Array index

Tags:

c++

c

pointers

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.

like image 771
Bill N. Avatar asked Aug 18 '11 20:08

Bill N.


People also ask

Is pointer arithmetic faster than array indexing?

Pointer arithmetic is actually about 30% faster than using array indexes.

Is an array index a pointer?

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.

Which is better pointer or array?

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.

Which is faster pointer or array?

Why ? pointers because it is direct memory access followed by dereferencing array - add current index to base address then dereferencing.


1 Answers

&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.)

like image 124
Keith Thompson Avatar answered Nov 15 '22 22:11

Keith Thompson