我想學習C,並且似乎無法弄清楚如何從字符串中讀取字符串到數組中。我有一個字符串數組的二維數組字符串,並試圖通過使用malloc來讀取這些字符串,但我一直在收到一個SegFault。有關如何修復我的代碼的任何提示?從字符串中讀取字符串到C中的動態分配數組中
#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]);
}
關於stdlib.h你說得對。這有幫助。我知道malloc是錯誤的,但我不知道如何使用它。 – Johnny 2013-05-01 03:09:33