我想弄清楚爲什麼我無法將文件存儲到char **中。Seg Fault char ** C
我以爲我正確分配了內存。有人可以幫幫我嗎?謝謝!另外,我知道我的方式並不是解決問題的最有效方式,但首先我想在擔心效率之前先完成問題。謝謝!
void readFile(int argc, char** argv)
{
FILE *myFile;
char** list;
char c;
int wordLine = 0, counter = 0, i;
int maxNumberOfChars = 0, numberOfLines = 0, numberOfChars = 0;
myFile = fopen(argv[1], "r");
if(!myFile)
{
printf("No such file or directory\n");
exit(EXIT_FAILURE);
}
while((c = fgetc(myFile)) !=EOF) //goes through the file to get # of lines
{ //and columns so I can allocate array
numberOfChars++;
if(c == '\n')
{
if(maxNumberOfChars < numberOfChars)
maxNumberOfChars = numberOfChars + 1;
numberOfLines++;
}
}
fseek(myFile, 0, SEEK_SET); //resets file pointer
list = malloc(sizeof(char*)*numberOfLines); //dynamically allocating
for(i = 0; i < wordLine ; i++)
list[i] = malloc(sizeof(char)*maxNumberOfChars);
while((c = fgetc(myFile)) != EOF) //stores in words
{
if(c == '\n' && counter > 0)
{
list[wordLine][counter] = '\0';
wordLine++;
counter = 0;
}
else if(c != '\n')
{
list[wordLine][counter] = c; //seg fault happens at first character
counter++;
}
}
fclose(myFile);
}
該學習調試程序了。並做代碼評論以發現明顯的錯誤。 – 2013-02-09 10:53:43