确定在C中创建时间后的动态阵列的长度
int *p = malloc(sizeof(int)*10);
size_t val = sizeof(p)/sizeof(int);
printf("this array (p) can content %lu elements \n",val);
大家好,
-
我一直在尝试使此程序打印“此数组(P)可以满足10个元素”。但这无效。 (对我而言,val的值被认为是此数组的长度。p除以p的一个元素的总元素的大小)
-
的一个元素,当我尝试在malloc之后打印sizeof(p)时,它不是等于4*10(40);
有人可以告诉我出了什么问题吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
p
是指指针,sizeof(p)
不是由malloc()
分配的数组的大小,而是大小指针本身,根据平台的不同(除其他外来的可能性),这可能是4或8。表达式
sizeof(a)/sizeof(a [0])
仅适用于数组,定义为int a [10];
或可能在编译时间确定的长度来自Intializer:int a [] = {0,2,4};
。没有可移植的方法可以从指针中检索由
malloc()
分配的块的大小。您必须单独跟踪大小。p
is a pointer,sizeof(p)
is not the size of the array that was allocated bymalloc()
, it is just the size of the pointer itself, which may be 4 or 8 depending on the platform (among other more exotic possibilities).The expression
sizeof(a) / sizeof(a[0])
only works for arrays, defined asint a[10];
or possibly with a length determined at compile time from the intializer:int a[] = { 0, 2, 4 };
.There is no portable way to retrieve the size of the block allocated by
malloc()
from the pointer. You must keep track of the size separately.请参阅其他答案,以及问题下的评论。您必须自己跟踪尺寸。这是一个基本演示:
输出:
如何在C
1中容器化一个动态分配的数组。制作
array_int_t_t
“int> int
s”的数组“容器”让它更进一步,然后将其作为整数数组将其作为整数。
容器:
用法:
2。添加
array_int_create()
构造函数或“出厂”功能以创建int
s的数组,然后再进一步:
添加创建功能:
并使用它:
3。[最佳]更新
array_of_int_create()
“ factory”功能以完全动态地分配数组容器加上阵列空间,然后将PTR返回到容器中这很正确,因为它没有完全动态分配。相反,它需要每个
array_int_t
才能静态分配,然后仅动态地分配数组的内存,而不是容器本身。实际上,我们需要动态分配容器和数组内存,因此让我们解决这个问题。这是一个完整而健壮的例子,并提供详细的评论。在此示例中,我可能更改了一些变量名称。
来自 in我的
ercaguy_hello_world
See the other answer, and the comments under the question. You must keep track of the size yourself. Here is a basic demo:
Output:
How to containerize a dynamically-allocated array in C
1. Make an
array_int_t
"array ofint
s" containerLet's take it one step further and containerize it as an array of integers.
Container:
Usage:
2. Add an
array_int_create()
constructor or "factory" function to create an array ofint
sAnd one step further:
Add a create function:
And use it:
3. [BEST] Update the
array_of_int_create()
"factory" function to fully dynamically allocate an array container plus the array space, and return a ptr to the containerBUT, that factory function above technically isn't quite right, as it's not fully dynamically allocated. Rather, it requires each
array_int_t
to be statically allocated, and then it simply dynamically allocates the memory for the array only, but not the container itself. We actually need to dynamically allocate both the container and the array memory, so let's fix that.Here is a full and robust example, with detailed comments. I may have changed some of the variable names in this example.
From containers_array_dynamic_array_of_int_with_factory_create_func.c in my eRCaGuy_hello_world repo:
Sample output: