2014-09-28 65 views
0

我想讀取由.dat文件中的空格分隔的名稱到我所做的結構數組中,但是我收到錯誤'運行時檢查失敗#2 - 堆棧變量'player_arr'被破壞'。 我是C新手,所以任何提示或指針,將不勝感激。堆棧周圍的變量''損壞在C

#include "stdafx.h" 
#include <stdio.h> 
#include <string.h> 

#define NAME_LEN 31      /*storage for single name*/ 
#define TEAMSIZE 14      /*creates teamsize 0-14 (15 total)*/ 

void readNames(); 

typedef struct{ 
    char name[NAME_LEN];     /*bowlers name ie 'jones'*/ 
    int oversLatest;      /*bowlers overs, latest and overall*/ 
    int maidensLatest;      /*bowlers maidens, latest and overall*/ 
    int runsLatest;       /*bowlers runs, latest and overall*/ 
    int wicketsLatest;      /*bowlers wickets, latest and overall*/ 
    int strikeRate;       /*bowlers strike rate*/ 
    double average;       /*average */ 
} player_t; 

FILE *input; 

int i, count; 
char c; 


int main(void) 
{ 
    readNames(); 

    return 0; 
} 


/* function to read input2a.dat and assign the name to the player_t structure 
*/ 
void readNames(){ 
    input = fopen("input2a.dat", "r");  /**/ 

    player_t player_arr[TEAMSIZE]; 
    count = 0; 

    do{ 
     c = fscanf(input, "%s", &player_arr[count].name); 
     printf_s("%s\n", player_arr[count].name); 
     count++; 
    } while (c != EOF); 
    fclose(input); 
} 
+4

開始。另外'c'應該是'int',並且在繼續執行'printf'和'count ++'之前,你應該檢查'fscanf'的結果。爲了改進你的代碼,使'c'和'count'是'readNames'中的局部變量。 – 2014-09-28 03:22:55

+2

爲防止'fscanf'溢出,請將''%s''改爲''%30s'''。考慮使用'fgets'來代替。 – 2014-09-28 03:23:56

+0

你不需要&player_arr [count] .name。數組變量也是指針。另外,請確保沒有任何名稱超過31個字符。基本上,你正在破壞player_arr變量上面或下面的物理堆棧內存,可能是因爲讀取的名字太長。編輯:馬特McNabb有原因,你可能會破壞堆棧...太多循環! – 2014-09-28 03:24:18

回答

0

破壞內存。

以下爲14個團隊分配內存,但評論意味着您的文件中有15個團隊。

// #define TEAMSIZE 14 /*creates teamsize 0-14 (15 total)*/ 
#define TEAMSIZE 15 /*creates teamsize 0-14 (15 total)*/ 
player_t player_arr[TEAMSIZE]; 

while可能循環得太遠。錯誤類型爲scanf()返回值。太遲檢查scanf()返回值是否好。 @馬特麥克納布
信息上printf_s

// char c; 
int c; 
while ((count < TEAMSIZE) && 
    ((ch = fscanf(input, "%30s", &player_arr[count].name)) == 1)) { 
    printf_s("%s\n", player_arr[count].name); 
    count++; 
} 

投保你是不是讀名過長。數組前面不需要&。 @ c.fogelklou

#define NAME_LEN 31      /*storage for single name*/ 
char name[NAME_LEN]; 
// c = fscanf(input, "%s", &player_arr[count].name); 
c = fscanf(input, "%30s", player_arr[count].name); 

未檢查文件打開是否成功。

input = fopen("input2a.dat", "r"); 
if (input == NULL) Handle_Failure(); 

最佳讀取文件的行與fgets()一個緩衝區,然後通過你的循環的打破,一旦`count`達到`TEAMSIZE`解析與scanf()strtok()該緩衝區等