[英]Seg Fault char** C
我試圖弄清楚為什么我不能將文件存儲到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);
}
這一點:
for(i = 0; i < wordLine ; i++)
wordLine
= 0,因此不會分配任何內存。 我認為應該是:
for(i = 0; i < numberOfLines; i++)
並且您需要將numberOfChars
= 0設置為類似於Grijesh Chauhan所說的,否則您將分配過多的內存。
您對字線的分配:
for(i = 0; i < wordLine ; i++)
list[i] = malloc(sizeof(char)*maxNumberOfChars);
使用wordLine
,但是您在一開始將其初始化為0,並且永遠不會更改。
因此,此for循環中的malloc永遠不會執行。
您的for
循環條件很混亂,
for(i = 0; i < wordLine ; i++)
list[i] = malloc(sizeof(char)*maxNumberOfChars);
wordLine
初始化為0
,未按預期執行,並在list[i]
分配了內存
您可能需要將其更改為
for(i = 0; i < numberOfLines ; i++)
list[i] = malloc(sizeof(char)*maxNumberOfChars);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.