[英]Segmentation fault whilst reading strings from a text file into a struct
我試圖將文件讀入包含char數組的結構中,如下面的代碼所示,但是它給出了分段錯誤的輸出:11.我已經嘗試了所有方法,包括使用類似的示例,但是我已經盡了全力。
我的代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 1024
struct Raw_Word{
char word[MAX_LENGTH];
char filename [25];
int length;
};
struct Final_Word{
char word[MAX_LENGTH];
int length;
int amount;
};
struct Raw_Word raw_word[MAX_LENGTH];
int main(int argc, char* argv[]) {
if (argc > 10) {
printf("Maximum of 10 files allowed");
return 1;
}
int i = 0;
int lines = 0;
for (i = 1; i <= argc; i++) {
FILE *fp = fopen(argv[i], "r");
while(fgets(raw_word[lines].word, MAX_LENGTH, fp)){
//printf("%s", raw_word[lines].word);
}
fclose(fp);
}
for(int j = 0; j < lines; j++){
printf("%s\n", raw_word[j].word);
}
return 0;
}
線
for (i = 1; i <= argc; i++)
是不正確的。 您需要在argc-1
處停止索引。
for (i = 1; i < argc; i++)
要么
for (i = 1; i != argc; i++)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.