c - 使用 malloc 为数组插入值

标签 c arrays malloc

我使用此代码插入数组 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;
}

最佳答案

  1. 打印循环应使用 i作为索引而不是 n作为你的
  2. 循环必须达到 n-1 ,所以正确的条件必须是 i<n 。您的代码访问“数组”越界,调用 Undefined Behavior
  3. 您始终必须检查函数返回值。
  4. 旁注:带有 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/

相关文章:

c++ - 字符串指针的 malloc : how it can be disastrous?

c - Malloc() 为整数创建新的大小以用于数学 - 需要指导

c - 为什么 Sublime Text 报告我的程序以退出代码 1 终止?

c - 符合 ANSI C 标准的平台,其中全零位不是空指针表示

java - 文件输入到 arrayList 中。用于创建新对象的相同 arrayList

c - 使用 Printf 打印二维数组元素

java - 在数组中使用 boolean 值的 If 语句

c - 为什么不在这种情况下使用 free()

python - Ctypes Windows错误: exception: access violation writing 0x0000000000000000 while calling a DLL function from another dll file

c - 如何在 C 中为 mysql 查询设置准备好的语句?