简体   繁体   中英

C++ why accessing dynamic array is used without the asterisk operator?

for example:

#include <iostream>
using namespace std;

int main(){
int *a;
a = new int[2];
a[1] = 1;

}

From what I understand, a 2 sized array of int is allocated in "the heap memory" and pointer a takes the memory address of that newly created array. However, when trying to access (for example) the second index of the array ( a[1] ), it simply does so without the asterisk operator and I don't understand why, I'm used to seeing that the value stored in a memory address pointed to by a pointer is accessed as *pointername and not like pointername[value] . So my question is, why do we use the subscript operator to access a pointer which points to an array without the asterisk operator?

In C++, applying operator[] to a pointer p with index i is the semantic equivalent of

*(p + i)

and

*(i + p)

You can think of it as syntactic sugar. Also note that this implies that p[N] is equivalent to N[p] .

a[N] is equal to *(a+N) if a is a pointer. Thus, a[1] dereferences the pointer a+1 .

An array is a block of memory containing multiple instances of same size elements, the subscript operator just puts an offset for the right element from the original pointer. so a[0] would be equal to *a. and a[1] = *a + 1 * sizeof(element) so in a sense you are right we do use the asterisk operator in the end it's just hidden behind syntactic sugar.

Ihe index operator has a peculiar meaning for an array of primitives: array[index] is equivalent to *(array+index) . One side effect is that if you want to obfuscate your code, index[array] means exactly the same thing (for primitive types, of course). For primitive arrays, the index operator is semantic sugar for a dereference.

For non-primitive types, classes can override operator[] . This is the opposite of semantic sugar.

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