c - 打印输出时出现段错误

标签 c arrays segmentation-fault

我想知道 c 中的数组是如何工作的。所以我正在实现一些基本的数组概念。当我运行该程序时,我得到了准确的输出,但在输出的末尾显示段错误

int main(void)
{
    int a[] = {};
    printf("Enter the number:");
    int n = get_int();
    int m = 0;

    for(int i = 0; i<n; i++)
    {
        printf("insert:");
        m = get_int();
        a[i] = m;
    }

    for(int j = 0; j < n; j++)
    {
        printf("%d\n", a[j]);
    }

}

输出:

Enter the number:3
insert:1
insert:2
insert:3
1
2
3
~/workspace/ $ ./arr_test
Enter the number:5
insert:1
insert:2
insert:3
insert:4
insert:5
1
2
3
4
5
Segmentation fault

查看第一个输出,它的大小为 3,它没有显示 segmentation fault 但对于第二个输出,它显示的大小为 5。那么为什么会这样,我犯了什么错误。

最佳答案

您需要为数组分配内存。像这样的东西:

int main(void)    {
   int *a;
   ...
   int n = get_int();
   ...
   a = malloc(n * sizeof(int));
   if (!a) {
      // Add error handling here
   }
   ...
}

关于c - 打印输出时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43106320/

相关文章:

c - 为什么 GCC 原子内置函数需要额外的 "generic"版本?

c - 解释这个 C 程序的工作

复制矩阵时出现 C++ 段错误

c++ - MPI + OpenMP 段错误和不可预测的行为

c - 为什么会出现段错误(C 中的信号量)?

c - 在 c 中返回 likely(x) 它是如何工作的?

c - write() 错误地址

arrays - 我怎样才能快速存储巨大的数组

JavaScript 高分表

javascript - 为函数内的全局数组赋值