Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C “的价值”;多维数组指针+;1“;不';不匹配_C_Arrays_Pointers - Fatal编程技术网

C “的价值”;多维数组指针+;1“;不';不匹配

C “的价值”;多维数组指针+;1“;不';不匹配,c,arrays,pointers,C,Arrays,Pointers,以下是问题程序: #include <stdio.h> int main() { int apricot[2][3][5]; int (*r)[5]=apricot[0]; int *t=apricot[0][0]; printf("%p\n%p\n%p\n%p\n",r,r+1,t,t+1); } 我认为t的维度值应该是5,因为t是最后一个维度,并且事实是匹配的(0xbfa44004-0xbfa44000+1=5) 但是r的维的值是0xb

以下是问题程序:

#include <stdio.h>
int main()
{   
    int apricot[2][3][5];
    int (*r)[5]=apricot[0];
    int *t=apricot[0][0];

    printf("%p\n%p\n%p\n%p\n",r,r+1,t,t+1);
} 
我认为t的维度值应该是5,因为t是最后一个维度,并且事实是匹配的(0xbfa44004-0xbfa44000+1=5)


但是r的维的值是0xbfa44014-0xbfa44000+1=21,我认为应该是3*5=15,因为3和5是最后两个维,那么为什么差值是21呢?

r
是指向5个整数数组的指针


假设系统上的1 int是4字节(从
t
t+1
),那么将指针“步进”1(
r+1
)意味着增加5*4=20字节。这就是你在这里得到的。

你被C语法欺骗了
r
是指向int数组的数组指针,
t
是普通int指针。当你做任何类型的指针运算时,你都要用指向的单位来做

因此,
t+1
意味着
t
+的地址,即指向对象的一个大小。由于t指向int,并且int在您的系统上是4个字节,因此您可以从
t
获得4个字节的地址

同样的规则也适用于
r
。它是指向5 int数组的指针。当您通过
r+1
对其进行指针运算时,您会得到指向对象的大小,该对象的大小
5*sizeof(int)
,恰好是您计算机上的20字节。因此,
r+1
r
中为您提供一个20字节(=14十六进制)的地址

# ./a.out 
0xbfa44000
0xbfa44014
0xbfa44000
0xbfa44004