C,malloc()和数组长度 [英] C, Malloc() and array length
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-an-array\">How找到的sizeof(指针指向一个数组)
我正在学习如何创建下的动态数组,但所遇到的一个问题,我想不通。
I'm learning how to create a dynamic array in C, but have come across an issue I can't figure out.
如果我使用code:
int num[10];
for (int i = 0; i < 10; i++) {
num[i] = i;
}
printf("sizeof num = %li\n sizeof num[0] = %li", sizeof(num), sizeof(num[0]));
我得到的输出:
sizeof num = 40
sizeof num[0] = 4
这是我所期待的事情发生。但是,如果我喜欢的malloc数组的大小:
This is what I'd expect to happen. However if I malloc the size of the array like:
int *num;
num = malloc(10 * sizeof(int));
for (int i = 0; i < 10; i++) {
num[i] = i;
}
printf("sizeof num = %li\n sizeof num[0] = %li", sizeof(num), sizeof(num[0]));
然后我得到的输出:
Then I get the output:
sizeof num = 8
sizeof num[0] = 4
我很好奇,想知道为什么数组的大小为40,当我使用固定长度的方法,而不是当我使用的malloc()
。
推荐答案
在第二种情况下, 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[]
.
这篇关于C,malloc()和数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!