gpt4 book ai didi

c - scanf 中的段错误

转载 作者:行者123 更新时间:2023-12-04 07:06:46 25 4
gpt4 key购买 nike

运行此代码时,我在 scanf() 处遇到段错误。这可能是由于大数组的声明(我通过注释数组声明来检查它)。

#include<stdio.h>
int main()
{
int test;
//int n,ok,counter,i,j;
char a[1000][1000];
int x[1000][1000],y[1000][1000];
scanf("%d",&test);
printf("%d",test);
return 0;
}

因为我需要这些数组,所以有人可以建议我如何纠正此代码。

最佳答案

问题是您正在本地定义一些巨大的对象。局部变量在堆栈上创建,并且堆栈有限制(每个线程)。有时堆栈最大可达 1 MB。你的数组将远远超出这个范围。我的猜测是你实际上溢出了堆栈。您可以将数组定义移到 main 之外,并且您的程序应该可以工作,因为这些数组不会在堆栈上创建。您还可以通过在 main 中将数组设置为 static 来定义数组。这与在外部声明它们具有相同的效果。

全局定义的变量(包括未初始化的数组)和静态未初始化的变量(即使它们在函数中)通常会放置在数据段中,并在程序运行时进行初始化。它们也保证被设置为全0。这个Wiki reference在 C 中将此数据区域描述为:

BSS in C

In C, statically-allocated objects without an explicit initializer are initialized to zero (for arithmetic types) or a null pointer (for pointer types). Implementations of C typically represent zero values and null pointer values using a bit pattern consisting solely of zero-valued bits (though this is not required by the C standard). Hence, the BSS section typically includes all uninitialized variables declared at file scope (i.e., outside of any function) as well as uninitialized local variables declared with the static keyword. An implementation may also assign statically-allocated variables initialized with a value consisting solely of zero-valued bits to the bss section.

BSS 段不像堆栈那样受到约束。如果资源存在并且您没有超出任何进程配额,BSS 可能会耗尽可用内存。

另一种选择是使用malloc动态分配数组,这会将它们放在堆上。以下代码是创建数组的最简单方法。我使用#define 来更清楚什么是行和列。定义这些数组并分配内存后,可以像任何普通的 2D 数组一样使用它们。

#include<stdio.h>
#include<stdlib.h>
int main()
{
#define ROWS 1000
#define COLUMNS 1000
int test;

char (*a)[COLUMNS] = malloc(ROWS * sizeof *a);
int (*x)[COLUMNS] = malloc(ROWS * sizeof *x);
int (*y)[COLUMNS] = malloc(ROWS * sizeof *y);

a[100][20] = 'X';
x[4][999] = 666;
y[500][0] = 42;

scanf("%d",&test);
printf("%d",test);

free(a);
free(x);
free(y);

return 0;
}

关于c - scanf 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26077874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com