[英]Solve segmentation fault error in C
我試圖使用此代碼將總和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\n", terms[i]);
y++;
i++;
e++;
}
}
我得到了“分段錯誤”錯誤。 為什么會這樣? 我怎么能避免呢?
我在C編程
n
是double terms[n];
垃圾double terms[n];
這會導致未定義的行為。 通過使用gcc -Wall
和observe編譯來啟用編譯器警告。 永遠不要忽視警告。
在聲明terms[n]
OR之前初始化n
printf(" Introduce n\n");
scanf("%d", &n);
double terms[n];
e
也未初始化,初始化它。
e = 0 ;
while (e < n){
/* code */
}
當聲明具有n
元素的數組( double terms[n];
)時,所述數組的分配在編譯階段完成。 因為你的n
變量未被初始化,所以它具有不確定的值(從用戶角度來看是隨機的),因此你不知道所述數組的大小是多少。
稍后將int
掃描到n
並沒有任何幫助,因為它在運行時完成(並且,它也是在數組聲明之后完成的。如果你在scanf
之后使用malloc
進行分配,它可能會有效)。
無論如何,你目前有一個“隨機”大小的數組,訪問它是Undefined Behavior - > segfault
崩潰來自terms[n]
數組的未定義大小。 您正在跨越陣列內存邊界。
一些變量未初始化:
double terms[n]; // n is not initialized
while (e<n){ // e is not initialized
您有很多選擇來正確構建terms
數組(在代碼中也標記):
1)預先確定陣列的具體大小。 (這不是靈活的方法!)
2)讀取n
時動態分配數組。
3)讀完n
后聲明terms[n]
。
測試程序:
#include <stdio.h>
#include <stdlib.h>
int main(){
int i;
int n;
int e = 0;
// 1. One of the 3 choices - thus is a rigid one
// double terms[TERMS_SIZE]; // make TERMS_SIZE big enough, read n has to be less than TERMS_SIZE
double x, y;
printf(" Introduce n\n");
scanf("%d", &n);
// 2.
// double *terms = malloc ( n* sizeof sizeof(double));
// or
// 3.
double terms[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++;
}
// If 2. used free the memory
// free(terms);
return 0;
}
輸出:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.