我使用此代码插入数组 data
的值,但是当我尝试插入值 8 1 2 3 4 5 6 7 8
时(第一个数字8是数组的大小),输出为 00000000
而不是输入值 1 2 3 4 5 6 7 8
。知道如何使该程序运行吗?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*data;
scanf("%d", &n);
data=(int *)malloc(sizeof(int)*n);//data[size]
for(i=0;i<n;i++)
{
scanf("%d", &data[i]);
}
for(i=0;i<=n;i++)
printf("%d",data[n]);
printf("\n");
return 0;
}
最佳答案
- 打印循环应使用
i
作为索引而不是n
作为你的 - 循环必须达到
n-1
,所以正确的条件必须是i<n
。您的代码访问“数组”越界,调用 Undefined Behavior - 您始终必须检查函数返回值。
- 旁注:带有 c you shouldn't cast malloc return .
代码
#include<stdio.h>
#include<stdlib.h>
int main()
{
size_t n,i;
int *data;
printf("Insert number of items: ");
scanf("%zu", &n);
data=malloc(sizeof(int)*n);
if (data != NULL)
{
for(i=0;i<n;i++)
{
printf("Insert value for item %zu: ", i+1);
scanf("%d", &data[i]);
}
printf("You inserted: ");
for(i=0;i<n;i++)
printf("%d ",data[i]);
}
else
{
fprintf(stderr, "Failed allocating memory\n");
}
printf("\n");
return 0;
}
关于c - 使用 malloc 为数组插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37478626/