我有以下代码,其中有指向二维数组的指针变量指针。
int main()
{
int (*ptr)[2][3];
printf("%u\n", sizeof(ptr)); // ---> give size of pointer = 8
printf("%u\n", sizeof(*ptr)); // ---> give size of array = 24, how it works adding * to ptr gives array size
return 0;
}
最佳答案
您必须将转换说明符 %zu
与类型为 size_t
的运算符 sizeof
返回的值结合使用。
printf("%zu\n", sizeof(ptr));
^^^^^
如果你有一个像这样的指针
T *p;
其中 T
是某种类型,则表达式 *p
的类型为 T
。因此 sizeof( *p )
等价于 sizeof( T )
。
本声明
int (*ptr)[2][3];
声明一个指向数组类型的指针int[2][3]
;您可以按以下方式使用 typedef 重写声明
typedef int T[2][3];
T *ptr;
因此表达式 sizeof( *ptr )
等价于表达式 sizeof( int[2][3] )
。
关于c - 它如何使用指向数组的指针计算数组的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69183414/