使用malloc为数组插入值

时间:2016-05-27 08:31:41

标签: c arrays malloc

我使用此代码插入数组data的值,但是当我尝试插入值8 1 2 3 4 5 6 7 8时(第一个数字8是数组的大小),输出为{{1}而不是输入值00000000。知道如何让程序运作吗?

1 2 3 4 5 6 7 8

2 个答案:

答案 0 :(得分:2)

您需要更改此部分:

for(i=0;i<=n;i++)
    printf("%d",data[n]);
    printf("\n");
    return 0;
}

到:

for(i = 0; i < n; i++)
    printf("%d",data[i]);
    printf("\n");
    return 0;
}

您现在所做的是迭代但不使用变量i作为索引。相反,您经常尝试仅打印data[n]。这是在中访问索引 越界 ,数组的索引从0开始并到达n-1,其中{{ 1}}是数组的大小。这可能导致程序的[tag:undefined-behavior]。

所以你的n循环必须是:

for

或:

for(i = 0; i < n; i++)

另外,请查看此link on why you should not cast the result of malloc。此外,请确保始终检查for(i = 0; i <= n-1; i++) 的结果,如下所示:

malloc

答案 1 :(得分:2)

  1. 打印循环应使用i作为索引,而不是n作为您的
  2. 循环必须达到n-1,因此正确的条件必须为i<n。您的代码访问“数组”超出界限,调用Undefined Behavior
  3. 您必须检查函数返回值。
  4. 附注: you shouldn't cast malloc return
  5. 代码

    #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;
    }