简体   繁体   中英

What does the array subscripting operator ([ ]) do to an array?

I'm wondering what the array subscripting operator ( [] ) do to objects

From this question and this question , I learnt that the [] operator takes an address of an object, adds whatever it is in between the brackets to the object and finally dereferences the sum to obtain an address. However, in array declarations, eg.

int iarr[] = {1,2};
int iarr2[2] = {1,2};

The [] operator doesn't seem to be adding the value in the brackets to the operand, especially in the second example. Instead, it seems to be giving the object the ability to store arrays.

Also, my wild guess is that in int arr2[2] = {1,2} , arr[2] will allocate memory for two int s. Is that true?

As a summary:

What does the [] operator do to its operand during declaration? Does it just give the object the ability to store arrays or does it allocated memory for the array instead?

[] is an operator only when applied to an expression.
(The same principle holds for & and * .)

In a declaration, it's part of the type and doesn't really "do" anything other than specify that the declared variable is an array.

You are confusing the [] operator and the syntax for declaring an array.

int iarr2[2] = {1,2};

is declaring an array named iarr2 of 2 integers and then initializing the elements of the array to 1 and 2. It is not applying the [] operator.

This:

int iarr[] = {1,2};

Means define an array which size will mach number of elements in initialization list.

On other hand:

 int iarr2[2] = {1,2};

Means define an two element array and initialize it to 1 and 2

You can do also:

 int iarr2[4] = {1,2};

Means define an four element array and initialize first two elements to 1 and 2 . Remaining elements are initialized to: 0

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