Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - when to use pointer arithmetic, when to use array indexing?

Tags:

arrays

c

pointers

In C, when is it preferrable to use one over the other?

like image 208
talloaktrees Avatar asked Jul 24 '12 06:07

talloaktrees


People also ask

Is pointer arithmetic faster than array indexing?

Pointer arithmetic is slightly faster (about %10) than array indexing.

Why pointer arithmetic is faster?

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.

Which is better pointer or array?

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.

Is 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.


1 Answers

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.

like image 180
Basile Starynkevitch Avatar answered Sep 28 '22 06:09

Basile Starynkevitch