user987362
user987362

Reputation: 377

Array of pointers in c++

If iptr is an array pointers then is there any difference between **(iptr+3) and *iptr[3]

Upvotes: 0

Views: 150

Answers (5)

rashok
rashok

Reputation: 13484

Both are same, Compiler will treat iptr[3] and 3[iptr] as *(iptr+3) and *(3+iptr) only.

int a[5][10] = {0}; Consider this 2 dimentional array. Here a[i][j] means *(*(a+i) + j), so we can write like i[a][j] also which means *(*(i + a) + j).

But i[j][a] is wrong, because it will be treated as *(*(i + j)+a) which is wrong. *(i+j) will leads to crash(undefined behaviour).

Upvotes: 0

Jepessen
Jepessen

Reputation: 12445

It's the same due to pointer arithmetic.

Suppose that you have a custom type

typedef struct
{
     /* add some parameters here */
} MyStruct;

And then create a vector of this type

MyStruct xMyStructArray[20];

When you want to access to, for example, the third element, you can do in one of following ways:

MyStruct xValue = xMyStructArray[2]; // index starts from zero
MyStruct xValue = xMyStructArray + 2;

xMyStructArray alone is seen as a pointer to the first array element.

xMyStructArray == &(xMyStructArray[0])

C/C++ creates an array in contiguous memory cells, and when you use the [] operator, you tell it to access to the respective cell of that array, starting from the pointer address corresponding to first array element address. So it knows the size of your type, and go to the right address.

The pointer arithmetic works the same. When you sum 1 to a pointer, the compiler checks the size of the type corresponding to that pointer, and then goes to the next position in memory compatible with that type.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 882646

To the compiler, no, there is no difference. Both forms end up accessing the same element.

However, if you're writing code for the compiler, you've got the wrong audience. Your code should be written as if the next person to maintain it is a psychopath who knows where you live.

In other words, code for readability and maintainability, and let the compiler itself worry about optimisations (a). To that end, I always prefer the array[index] form over the *(array+index) one since the former clarifies intent: the accessing of an array element.


(a) Of course, as with most rules, there are exceptions. But, as with most exceptions, they're few and far between, so that advice stands.

Upvotes: 0

NullPoiиteя
NullPoiиteя

Reputation: 57332

there are nothing same between the **(iptr+3) and *iptr[3] since

*iptr[3] is the pointer representing the element having the address no-3 in the array

**(iptr+3) and it's like if iptr is 3 than its **(6)

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258678

No, and, surprisingly (or not), also equivalent to *(3[iptr]).

Upvotes: 4

Related Questions