我正在尝试学习 C,但似乎无法弄清楚如何将文件中的字符串读入数组。我有一个二维字符数组作为字符串数组,并尝试使用 malloc 读取这些字符,但我不断收到 SegFault。关于如何修复我的代码的任何提示?
#include <stdio.h>
#define MAX_WORDS 10
#define MAX_WORD_SIZE 20
unsigned int getLine(char s[], unsigned int uint, FILE *stream);
int main( void ){
FILE *infile1;
unsigned int i = 0;
unsigned int j = 0;
unsigned int index;
char c;
char wordList[ MAX_WORDS+1 ][ MAX_WORD_SIZE + 1];
infile1 = fopen("myFile.txt", "r");
if (!(infile1 == NULL))
printf("fopen1 was successful!\n");
while( (c = getc(infile1)) != EOF){
while ((c = getc(infile1)) != ' '){
wordList[i] = (char *)malloc(sizeof(char) );
wordList[i][j] = getc(infile1);
j++;
}
j = 0;
i++;
}
printf("\nThe words:\n");
for (index = 0; index < i; ++index){
printf("%s\n", wordList[index]);
}