数组和指针算术〜需要澄清

时间:2013-09-09 14:39:45

标签: c arrays pointers multidimensional-array pointer-arithmetic

我正在做一些关于数组和指针的实验:

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]);

输出结果为:

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

我理解1,2,4,5,6,8和9的输出。但我不明白3和7的输出。
为什么输出7

2 个答案:

答案 0 :(得分:10)

由于运算符[]的优先级高于运算符*,因此使用以下表达式:

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

等于:

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

也等于:

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

在这种情况下等于:

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

意味着ij最终都会将第一个索引移至p指向元素a[2][0],其值为7


[]*运算符优先考虑这个表达式的评估?使用()进行简单测试以确保首先评估*就足够了。这意味着:

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

等于:

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

这不过是简单的:

int y = a[i][j];

答案 1 :(得分:1)

让我们说a+ib

                        +--------------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

p=a同样的情况,类似于使用b