In C, when is it preferrable to use one over the other?
Pointer arithmetic is slightly faster (about %10) than array indexing.
Because memory allocation of array is continuous. So accessing array is much faster compare to pointer where memory allocation might or might not be continuous.
An array is a collection of elements of similar data type whereas the pointer is a variable that stores the address of another variable. An array size decides the number of variables it can store whereas; a pointer variable can store the address of only one variable in it.
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.
It is really a matter of style and of coding conventions, since in C p[i]
is defined to be the same as *(p+i)
where p
is a pointer and i
an integral index. AFAIK you could even write i[p]
but that is ugly.
This is not always true in C++ (which gives you the power of defining operator []
etc...).
I personally dislike hand-coding &p[i]
and prefer p+i
in that case.
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