2013-05-01 75 views
1

我想学习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]); 
} 

回答

0

你是如何编译这个的。编译器应该给你和错误的赋值:

wordList[i] = (char *)malloc(sizeof(char)); 

数组wordlist的类型是char *

而且你缺少一个包括的malloc不(stdlib.h中可能),你不应该从malloc投射返回。

+0

关于stdlib.h你说得对。这有帮助。我知道malloc是错误的,但我不知道如何使用它。 – Johnny 2013-05-01 03:09:33

0

一个明显的问题 - 您为wordList [i]分配一个字符,然后像使用每个wordList [i] [j]的字符一样使用它。

您不需要在此分配任何内存,因为您已将wordlist定义为2维数组而不是指针数组或类似数组。

下一个明显的问题 - 你正在阅读的字符,并没有提供字符串的结束,所以如果你有到最后的printf(),你将继续前进,直到碰巧有一个0的地方或在wordList [index]之后 - 或运行内存结束时,使用Segfault。

下一个问题 - 你是否打算在阅读一个空间后立即检测EOF - 并扔掉替代字符?

+0

摆脱了malloc,并添加在一行中,以0结尾的单词。不知道如何解决你提到的最后一个问题。 ((c = getc(infile1))!= EOF){ while((c = getc(infile1))!='')if((c = getc(infile1))= EOF){ { wordList [i] [j + 1] ='0'; return 0; \t \t} \t wordList [i] [j] = getc(infile1); \t j ++; } wordList [i] [j + 1] ='0'; j = 0; i ++; '}' – Johnny 2013-05-01 02:57:26

+0

'而((C = GETC(infile1))!= EOF){ 而((C = GETC(infile1))!='“){ \t单词表[i] [j] = getc(infile1); \t j ++; } wordList [i] [j + 1] ='0'; j = 0; i ++; }' – Johnny 2013-05-01 03:04:05

相关问题