简体   繁体   中英

Array of pointers in c++

如果iptr是数组指针,则**(iptr+3)*iptr[3]之间没有任何区别。

不,而且令人惊讶地(或不是),它也等效于*(3[iptr])

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)

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM