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);
}
開始。另外'c'應該是'int',並且在繼續執行'printf'和'count ++'之前,你應該檢查'fscanf'的結果。爲了改進你的代碼,使'c'和'count'是'readNames'中的局部變量。 – 2014-09-28 03:22:55
爲防止'fscanf'溢出,請將''%s''改爲''%30s'''。考慮使用'fgets'來代替。 – 2014-09-28 03:23:56
你不需要&player_arr [count] .name。數組變量也是指針。另外,請確保沒有任何名稱超過31個字符。基本上,你正在破壞player_arr變量上面或下面的物理堆棧內存,可能是因爲讀取的名字太長。編輯:馬特McNabb有原因,你可能會破壞堆棧...太多循環! – 2014-09-28 03:24:18