Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arrays and pointer arithmetic ~ clarification needed

I'm doing some experiment about arrays and pointers:

int a[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int i = 1, j = 1;
int (*p)[3];

p = a;
printf ("*(*(a + i) + j) = %d\n", *(*(a + i) + j));
printf ("*(a[i] + j) = %d\n", *(a[i] + j));
printf ("*(a + i)[j] = %d\n", *(a + i)[j]);
printf ("*(a + 3 * i + j) = %p\n", *(a + 3 * i + j));
printf ("*(*(p + i) + j) = %d\n", *(*(p + i) + j));
printf ("*(p[i] + j) = %d\n", *(p[i] + j));
printf ("*(p + i)[j] = %d\n", *(p + i)[j]);
printf ("*(p + 3 * i + j) = %p\n", *(p + 3 * i + j));
printf ("p[i][j] = %d\n", p[i][j]);

The output is:

1. *(*(a + i) + j) = 5
2. *(a[i] + j) = 5
3. *(a + i)[j] = 7
4. *(a + 3 * i + j) = 0x7fff5e0e5b94
5. *(*(p + i) + j) = 5
6. *(p[i] + j) = 5
7. *(p + i)[j] = 7
8. *(p + 3 * i + j) = 0x7fff5e0e5b94
9. p[i][j] = 5

I understand output of 1, 2, 4, 5, 6, 8 and 9. But I don't understand output of 3 and 7.
Why is the output 7?

like image 944
user159 Avatar asked Sep 09 '13 14:09

user159


2 Answers

Because the precedence of the operator [] is higher than the operator *, the following expression:

int x = *(a + i)[j];

is equal to:

int* p = (a + i)[j];
int  x = *p;

which is also equal to:

int* p = ((a + i) + j);
int  x = *p;

which in this case is equal to:

int  (*p0)[3]  = (a + i);
int*  p        = (p0 + j);
int   x = *p;

meaning that both i and j eventually shift the first index making p to point to element a[2][0], value of which is 7


And what has precedence of [] and * operators to do with the evaluation of this expression? Simple test by using () to make sure that * will be evaluated first will suffice here. Meaning that this:

int y = (*(a + i))[j];

is equal to:

int y = *(a[i] + j);

which is nothing but simple:

int y = a[i][j];
like image 124
LihO Avatar answered Sep 19 '22 05:09

LihO


Lets say a+i is b

                        +--------------a+0---> {1, 2, 3, 
                        |              a+1--->  4, 5, 6, 
                        |              a+2--->  7, 8, 9};
                        |
*(a + i)[j] =       *(*(b+j)) = *(*(b+1)+1) 
                              = *(*(b+2))
                              = *(*(a+2))
                              = **(a+2) 
                              = a[2][0]
                              = 7

int (*p)[3]; // Is pointer to array of 3 int s

When p=a same scenario , similar to using b

like image 32
P0W Avatar answered Sep 20 '22 05:09

P0W