C语言 获取C中动态分配数组的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5126353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the length of dynamically allocated array in C
提问by kranthi117
Possible Duplicate:
length of array in function argument
可能的重复:
函数参数中的数组长度
How do I get the length of a dynamically allocated array in C?
如何在 C 中获取动态分配数组的长度?
I tried:
我试过:
sizeof(ptr)
sizeof(ptr + 100)
and they didn't work.
他们没有工作。
回答by Felice Pollano
You can't. You have to pass the length as a parameter to your function. The size of a pointer is the size of a variable containing an address, this is the reason of 4 ( 32 bit address space ) you found.
你不能。您必须将长度作为参数传递给您的函数。指针的大小是包含地址的变量的大小,这就是您找到 4(32 位地址空间)的原因。
回答by AndersK
Since malloc just gives back a block of memory you could add extra information in the block telling how many elements are in the array, that is one way around if you cannot add an argument that tells the size of the array
由于 malloc 只返回一块内存,您可以在块中添加额外的信息来告诉数组中有多少元素,如果您不能添加一个告诉数组大小的参数,这是一种解决方法
e.g.
例如
char* ptr = malloc( sizeof(double) * 10 + sizeof(char) );
*ptr++ = 10;
return (double*)ptr;
assuming you can read before the array in PHP, a language which I am not familiar with.
假设您可以在 PHP(一种我不熟悉的语言)中读取数组之前的内容。
回答by datenwolf
回答by Henno Brandsma
Here you see the dangers of C: a ptr just points to memory and has no way of knowing what supposed size is. You can just increment and increment and the OS might complain eventually, or you crash your program, or corrupt other ones. You should always specify the size, and check bounds yourself!
在这里您可以看到 C 的危险:ptr 只指向内存,无法知道假定的大小是多少。你可以不断地增加和增加,操作系统最终可能会抱怨,或者你的程序崩溃,或者破坏其他程序。您应该始终指定大小,并自己检查边界!

