解决C语言中的分段错误
我正在尝试使用以下代码将总和1/k^2存储在数组中:解决C语言中的分段错误,c,segmentation-fault,C,Segmentation Fault,我正在尝试使用以下代码将总和1/k^2存储在数组中: int main() { int i,n, e; double terms[n]; double x, y; printf(" Introduce n\n"); scanf("%d", &n); y=1; i=0; while(e<n) { x=1/((y)*(y)); printf("x is %.16lf\n",x); terms[i]=x; printf("terms is %.16lf
int main()
{
int i,n, e;
double terms[n];
double x, y;
printf(" Introduce n\n");
scanf("%d", &n);
y=1;
i=0;
while(e<n)
{
x=1/((y)*(y));
printf("x is %.16lf\n",x);
terms[i]=x;
printf("terms is %.16lf\n", terms[i]);
y++;
i++;
e++;
}
}
intmain()
{
int i,n,e;
双项[n];
双x,y;
printf(“介绍n\n”);
scanf(“%d”和“&n”);
y=1;
i=0;
而(en
在双项[n]中是垃圾;
会导致未定义的行为。通过使用gcc-Wall
编译启用编译器警告并遵守。切勿忽略警告
在声明术语[n]之前初始化n
,或
printf(" Introduce n\n");
scanf("%d", &n);
double terms[n];
而且e
未初始化,请初始化它
e = 0 ;
while (e < n){
/* code */
}
e=0;
while(e
当声明包含n
元素(双项[n];
)的数组时,所述数组的分配在编译阶段完成。由于未初始化n
变量,因此它的值不确定(从用户角度来看是随机的),因此您不知道所述数组的大小
稍后将int
扫描到n
中根本没有帮助,因为它是在运行时执行的(而且也是在数组声明之后执行的。如果在scanf
之后使用malloc
分配,它可能会起作用)
无论如何,您当前有一个大小为“随机”的数组,访问它是未定义的行为->segfault崩溃源于术语[n]
数组的未定义大小。您正在跨越数组内存边界
有几个变量未初始化:
double terms[n]; // n is not initialized
while (e<n){ // e is not initialized
输出:
4
Introduce n
x is 1.0000000000000000
terms is 1.0000000000000000
x is 0.2500000000000000
terms is 0.2500000000000000
x is 0.1111111111111111
terms is 0.1111111111111111
x is 0.0625000000000000
terms is 0.0625000000000000
当您定义数组术语时,n
的值是多少?您还没有初始化它,因此它是不确定的,看起来是随机的。代码不会返回并追溯重新定义变量。不相关,但是为什么while
而不是的?哦,您还使用其他未初始化的变量。只是不要这样做不要这样做!而且,这甚至会编译吗?因为n
没有定义编译时(用于初始化术语
数组)?@Neijwiert C99引入,因此它是有效的。C99还引入了声明和定义的自由放置,因此术语
的定义可以在初始化之后进行。
4
Introduce n
x is 1.0000000000000000
terms is 1.0000000000000000
x is 0.2500000000000000
terms is 0.2500000000000000
x is 0.1111111111111111
terms is 0.1111111111111111
x is 0.0625000000000000
terms is 0.0625000000000000