gpt4 book ai didi

c - 下面如何进行多维数组的指针运算?

转载 作者:行者123 更新时间:2023-11-30 19:04:03 24 4
gpt4 key购买 nike

这里 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 - 下面如何进行多维数组的指针运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52985296/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com