c - 下面如何完成多维数组的指针运算?
问题描述
这里 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
解决方案
这是因为您使用了不正确的指针类型。事实上,编译器甚至会告诉你:
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) == 4
和a
位于地址 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));
推荐阅读
- c# - [Xamarin]如何将列表中的结果绑定到Listview中?
- asp.net - ASP.NET Core 2.1 无法转换 IServiceProvider
- ruby-on-rails - Rails:使用 CarrierWave 作为 JS 而不是 HTML 处理表单
- c++ - 如何从几乎排序的链表中分离错位的元素?
- php - 以 DateFormat 为 Key 对多维数组进行排序
- angular - 无法使用 angularfire2 访问 Angular 6 应用程序中的多个 Google Firestore DB
- typescript - Chrome 开发者控制台中的 Typescript 文件已过期
- css - Material Design Lite 徽章更改颜色
- javascript - Javascript 承诺卡在挂起状态
- swift - 如何按值查询firebase?