왜 문자를 char **에 저장할 수 없는지 알아 내려고합니다.Seg 오류 문자 ** 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);
}
이제 프로그램을 디버깅하는 법을 배워 볼 차례입니다. 그리고 명백한 실수를 찾아내는 코드 리뷰를하십시오. –