#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
int *num=malloc(sizeof(int)*n);
printf("Enter how many numbers:\n");
scanf("%d",&n);
printf("Enter numbers:\n");
for(int i=0;i<n;i++)
{
scanf("%d",num+i);
}
for(int j=0;j<n;j++)
{
printf("%d\n",*(num+j));
}
return 0;
}
即使我没有在这里初始化 n,malloc 如何工作?有什么方法可以检查用 malloc 分配的数组的大小?
最佳答案
您可以在分配时将整个长度加到 1,并在第一个元素中保留 n 作为长度。如果您想从数组中获取某些内容,只需将 1 添加到索引即可。
关于c - 返回 mallocatted 数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54956122/