我想知道 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/