且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 C 中查找 malloc() 数组长度?

更新时间:2023-11-07 08:55:16

在第二种情况下,num 不是数组,是指针.sizeof 为您提供指针的大小,在您的平台上似乎是 8 个字节.

In the second case, num is not an array, is a pointer. sizeof is giving you the size of the pointer, which seems to be 8 bytes on your platform.

没有办法知道动态分配的数组的大小,您必须将其保存在其他地方.sizeof 查看类型,但不能从结果中得到完整的数组类型(指定大小的数组类型,如int[5]类型)malloc 以任何方式,并且 sizeof 参数不能应用于不完整的类型,例如 int[].

There is no way to know the size of a dynamically allocated array, you have to save it somewhere else. sizeof looks at the type, but you can't obtain a complete array type (array type with a specified size, like the type int[5]) from the result of malloc in any way, and sizeof argument can't be applied to an incomplete type, like int[].