我的 C 程式自行結束,我無法弄清楚問題所在。我在它停止的回圈上方添加了一條評論。
我正在創建一個程式來將陣列中的 dna 樣本相互匹配。dna 樣本是浮點數,我正在從檔案中讀取它們。
這是我正在閱讀的檔案:
2.3 3.3 4.5 6.7 7.8 2.1 3.2 4.3 5.2 6.5
5
2.3 3.3 4.5 6.7 7.8 2.1 3.2 4.3 5.2 6.5
1.3 0.3 9.5 8.7 5.8 4.1 3.2 2.3 6.2 6.9
6.3 9.3 4.3 6.4 7.5 2.9 3.0 4.1 5.3 6.5
6.1 9.4 4.5 6.6 7.4 2.8 3.2 4.4 5.0 6.0
2.3 3.3 4.5 6.6 7.8 2.2 3.2 4.3 5.2 6.5
預期的輸出是將列印所有值(犯罪樣本的 5 行),第一行將匹配,其余的將不匹配。然而,這是我的輸出:
Reading chromosomes of the suspect.
2.3 3.3 4.5 6.7 7.8 2.1 3.2 4.3 5.2 6.5
Reading chromosomes of the criminals.
2.3 3.3 4.5 6.7 7.8 2.1 3.2 4.3 5.2 6.5
1.3 0.3 9.5 8.7 5.8 4.1 3.2 2.3 6.2
我曾嘗試除錯它,有一次它在回圈期間隨機將我的 sizeR 變數分配為 10000 或其他值,我認為這是某個地方的問題,但現在不是我正在努力理解為什么它仍然為我停止。
代碼:
#include <stdio.h>
#include <stdbool.h>
FILE *fp;
int main(){
fp = fopen("dna_input.txt", "r");
int sizeR = 0, sizeC = 10; // declare size variables
float suspect[sizeC]; // declaring suspect array
float criminal[sizeR][sizeC]; // declaring criminal array
// reads 10 input values from first line of the file
printf("Reading chromosomes of the suspect. \n");
for (int i = 0; i < sizeC; i ){
fscanf(fp, " %f", &suspect[i]);
printf("%.1f ", suspect[i]);
}
printf("\n");
// reads integer from 2nd line of file for the amount of lines to read for next loop
fscanf(fp, " %d", &sizeR);
printf("Reading chromosomes of the criminals. \n");
// read 10 input values into 5 criminal arrays
// THIS LOOP IS WHERE MY PROGRAM IS STOPPING <---------------------------------------------
for (int i = 0; i < sizeR; i ){
for (int j = 0; j < sizeC; j ){
fscanf(fp, " %f", &criminal[i][j]);
printf("%.1f ", criminal[i][j]);
}
printf("\n");
}
// check for match
bool match = true;
for (int i = 0; i < sizeR; i ){
for (int j = 0; j < sizeC; j ){
if (suspect[j] != criminal[i][j]){
match = false;
}
}
// display matching result
if (match)
printf("The two profiles match! \n");
else
printf("The two profiles don't match! \n");
}
fclose(fp);
return 0;
}
uj5u.com熱心網友回復:
您需要動態分配罪犯陣列。
//Here sizeR is 0 so you are declaring criminal[0][10]
float criminal[sizeR][sizeC]; // declaring criminal array
典型的緩沖區溢位問題。
uj5u.com熱心網友回復:
謝謝你的評論,我完全錯過了。在 fscanf 之后,我已經移動了我的犯罪陣列
// reads integer from file for the amount of lines to read
fscanf(fp, " %d", &sizeR);
// declare criminal aray
float criminal[sizeR][sizeC];
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/351540.html
