Question

I'm trying to figure out why I can't store a file into char**.

I thought I allocated memory correctly. Can someone please help me? Thank you!

Also, I know my way isn't the most efficient way to go about the problem, but first I want to get the problem done before I worry about efficiency. Thank you!

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);
}
Was it helpful?

Solution

At this point:

for(i = 0; i < wordLine ; i++)

wordLine = 0, so no memory will be allocated. I think it should be:

for(i = 0; i < numberOfLines; i++)

And you need to set numberOfChars = 0, similar to what Grijesh Chauhan said, otherwise you'll allocate too much memory.

OTHER TIPS

Your allocation for the word lines:

for(i = 0; i < wordLine ; i++)
    list[i] = malloc(sizeof(char)*maxNumberOfChars);

uses wordLine, but you initialise this to 0 at the beginning, and it is never changed.

Therefore, the malloc in this for loop never executes.

Your for loop condition is messed,

for(i = 0; i < wordLine ; i++)
    list[i] = malloc(sizeof(char)*maxNumberOfChars);

wordLine is initialized to 0, it does not execute as expected and allocate memory in list[i]

You may want to change it to

for(i = 0; i < numberOfLines ; i++)
    list[i] = malloc(sizeof(char)*maxNumberOfChars);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top