我试图弄清楚为什么我不能将文件存储到 char** 中。
我以为我正确分配了内存。有人可以帮帮我吗?谢谢!
另外,我知道我的方法不是解决问题的最有效方法,但首先我想在担心效率之前解决问题。谢谢!
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);
}