tags:

views:

98

answers:

5

Let's say I have this line of code in a program:

int * number=0;
int mystery=&6[number];

Mistery is a number and I can use &5 or &4 obtaining other numbers.

But what does the "&6[]" mean?

Thanks!

+4  A: 

6[variable] is another less readable way of expressing variable[6]. It works because of the commutativity of the addition: variable[6] is the same as *(variable + 6), hence 6[variable] is the same as *(6 + variable).

zneak
+6  A: 

6[number] is exactly equivalent to number[6], so you're getting the address that's six integers away from number. Since number is 0 and an int is 4 bytes long, the result is 24.

RichieHindle
Well, `number + 24`.
zneak
A: 

This looks like the nauseating a[0] == 0[a] "feature" of C, so you could think of it as "the address of index 6 in the array number"

Nick T
A: 

6[number] is the same as number[6].

This is interpreted as the value the sixth element (*(number + 6*sizeof(int))) and since number is zero and sizeof(int) is usually 4, then its the value at address 24.

The & then gets the address of the value at address 24, thus mystery is equal to 24.

[EDIT] An int is typically 4 bytes long, so the correct value is 24.

Jaime Soto
birryree
Jaime Soto
+1  A: 

I have to point out that *(variable + 6) is not exactly like variable[6], this works only because the compiler knows the size of objects referred by the variable (int is 4 bytes in size), so what really happens is adding pointers: variable + 6*sizeof(int). It's just abstracted by the compiler.

I'm not quite sure (what's more, it may depend on the compiler), but with an array of structures this may not work because this struct is twice the size of the int:

struct a {
 int a;
 int b;
};

struct a arr[5];

int nmb;

struct a *res = nmb[arr]
Hubert Kario