首页 > 解决方案 > 下面如何完成多维数组的指针运算?

问题描述

这里 e 应该是 a[1] 处的地址,a 是 a[0] 处的地址。然后减去它将是 1,但结果是它们之间的总字节数。此处未应用指针算术。(忽略警告)。

int a[10][20][30] = {0};
int *d = a;
int *e = a+1;
printf("%ld", e-d);//why is this not 1

标签: carrayspointersmultidimensional-array

解决方案


这是因为您使用了不正确的指针类型。事实上,编译器甚至会告诉你:

prog.c: In function ‘main’:
prog.c:5:11: error: initialization from incompatible pointer type [-Werror=incompatible-pointer-types]
  int *d = a;

如果我们通过强制类型转换强行克服错误,编译器将使用这些错误的类型进行计算:

int a[10][20][30] = {0};
int *d = (int*)a;
int *e = (int*)(a+1);
printf("%ld", (long)(e-d));

请记住,当减去指针时,编译器使用的内部公式是(address2 - address1) / sizeof(type). 如果sizeof(int) == 4a位于地址 1000,则为(3400 - 1000) / 4 == 600

使用正确的类型 ( sizeof(int[20][30]) == 2400) 可以得到答案(3400 - 1000) / 2400 == 1

int a[10][20][30] = {0};
int (*d)[20][30] = a;
int (*e)[20][30] = a+1;
printf("%ld", (long)(e-d));

推荐阅读