我試圖讀取文件內容並將它們存儲到結構中,出於某種原因,我一直在收到段錯誤。請幫助我,我也不太瞭解valgrind。C編程中的結構
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int day;
int month;
int year;
char text[401];
} journal;
int main(int argc, char** argv){
int i, numberEntries;
FILE* fp = fopen(argv[1], "r");
fscanf(fp,"%d", &numberEntries); /* reads value on first line of file for number of entries */
printf("%d", numberEntries); /* check that it worked */
journal *entryArray ;
entryArray = (journal*)malloc(sizeof(journal));
if(fp == NULL){
perror("Error opening file");
} else {
for(i=0; i<4; i++){
fscanf(fp,"%d/%d/%d", entryArray[i].day, entryArray[i].month, entryArray[i].year);
fgets(entryArray[i].text, 400, fp);
printf("%s", entryArray[i].text);
}
}
for(i=0; i<4; i++){
printf("%d %d %d", entryArray[i].day, entryArray[i].month, entryArray[i].year);
printf("%s", entryArray[i].text);
}
free(entryArray);
return 0;
}
更新後的代碼仍然給出了段錯誤。
typedef struct {
int day;
int month;
int year;
char text[401];
} journal;
int main(int argc, char** argv){
int i, numberEntries;
FILE* fp = fopen(argv[1], "r");
if(fp == NULL){
perror("Error opening file");
} else {
fscanf(fp,"%d", &numberEntries); /* reads value on first line of file for number of entries */
printf("%d", numberEntries); /* check that it worked */
journal *entryArray ;
entryArray = (journal*)malloc(numberEntries*sizeof(journal));
for(i=0; i<4; i++){
fscanf(fp,"%d/%d/%d", &entryArray[i].day, &entryArray[i].month, &entryArray[i].year);
fgets(entryArray[i].text, 400, fp);
printf("%s", entryArray[i].text);
}
for(i=0; i<4; i++){
printf("%d/%d/%d", entryArray[i].day, entryArray[i].month, entryArray[i].year);
printf("%s", entryArray[i].text);
}
free(entryArray);
}
return 0;
}
輸入文件
4
12/04/2010
Interview went well I think, though was told to wear shoes.
18/04/2010
Doc advised me to concentrate on something... I forget.
03/05/2010
Was asked today if I was an art exhibit.
19/05/2010
Apparently mudcakes not made of mud, or angry wasps.
使用gdb來在你的代碼段錯誤得到抵消。根據情況,segfault可能在任何地方出現。所以這樣很難幫助你。 – 2014-10-09 04:06:54