2015-07-10 81 views
1

似乎一切都在我的程序試圖返回0這是當我得到的錯誤,除了運行良好:信號SIGABRT 0

Thread_1: signal SIGABRT 

我不知道我在做什麼錯,但我認爲,它可能是我如何使用我的指針(通過引用傳遞一個雙精度數組)。我相信這與當我的記憶被釋放時有關,我有點新,所以很難弄清楚這一點。謝謝!

編輯:readGrades()被從文本文件中讀取input.txt中4個整數,並將它們添加到在

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 

/* 
* readGrades() 
* INPUT: double array of grades (double grades[]) 
* OUTPUT: number of grades read (int numOfGradesRead) 
*/ 
int readGrades(double (*grades)[]) { 

int numOfGradesRead = 0, 
    count = 0, 
    numRead; 

char buf[1000]; 
FILE *file = fopen("input.txt", "r"); 

if (file == NULL) { 
    perror("Can't open file"); 
} else { 
    while (fgets(buf, sizeof(buf), file)) { 

     // Convert buf to integer 
     numRead = atoi(buf); 

     // Add number read to grades[] 
     if (numRead != -999) { 
      (*grades)[count] = numRead; 
      numOfGradesRead++; 
      count++; 
     } 
    } 
} 

fclose(file); 

return numOfGradesRead; 
} 

void frequency(double grades[], int numOfGrades) { 

} 

int main() { 

double grades[100]; 
int i; 

// Initialize grades values to 0 
for (i = 0; i < sizeof(grades)/sizeof(int); i++) { 
    grades[i] = 0; 
} 

int numOfGradesRead = readGrades(&grades); 

for (i = 0; i < 4; i++) { 
    printf("%f", grades[i]); 
} 

return 0; 
} 

回答

4

一個主要錯誤傳遞的陣列的行:

for (i = 0; i < sizeof(grades)/sizeof(int); i++) { 

由於該錯誤,您正在使用無界索引設置grades元素的值,這會導致未定義的行爲。

應該

for (i = 0; i < sizeof(grades)/sizeof(double); i++) { 
            // ^^^^^^^ Needs to be double not int 

可以使用常規

for (i = 0; i < sizeof(grades)/sizeof(grades[0]); i++) { 

使你的代碼更健壯。

而且,使用for循環中的硬編碼編號4來打印等級,您可能需要使用numOfGradesRead。另外,在等級之間打印空格或換行符以使輸出更易於閱讀。

for (i = 0; i < numOfGradesRead; i++) { 
    printf("%f\n", grades[i]); 
} 
+0

嗯看起來像這樣也解決了這個問題!非常感謝,我沒有發現這個錯誤。謝謝你的其他指針,真的很有幫助。 – Brejuro