繁体   English   中英

段故障字符** C

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM