0

I have created a struct in which I am trying to store whole text from file. The problem is that pointers and memory allocation does not want to collaborate with me.

typedef struct Text{
    char **line;
} Text;

After many variations, at this time, readFile function looks like this: It prints only the first line from file (there are 4 lines).

#define LINE_LENGTH 255
void readFile(FILE *inputPtr, char *inputFileName, Text *textInFile, unsigned lineIndex) {   
    while(!feof(inputPtr)) {
        ++lineIndex;
        textInFile->line = realloc(textInFile->line, LINE_LENGTH * lineIndex * sizeof(char));
        fgets(textInFile->line[lineIndex], LINE_LENGTH, inputPtr;
        //testing
        printf(textInFile->line[lineIndex]);
    }
}

I would be very thankful if you could help, how this function should look?

I have tried many different * and () placements, but could not make it work. If **line in struct is replaced with line[100][255] and mem. alloc. line is removed, then everything works well.

vabalas
  • 5
  • 3
  • 1
    As always: [Why is “while( !feof(file) )” always wrong?](https://stackoverflow.com/q/5431941/2505965) – Oka Nov 16 '22 at 19:39
  • Could you post more code? How is `textInFile` initialized (outside of this function)? – Jason Nov 16 '22 at 19:39
  • `sizeof(char)` being used in a calculation for the size of an allocation of `char *` objects looks dubious. It's always `1`, in any case. Additionally, you are trying to create a jagged array, but are only allocating the first of two dimensions. – Oka Nov 16 '22 at 19:40

1 Answers1

0
  1. It is not dynamically allocated array only double pointer.
  2. Why is “while( !feof(file) )” always wrong?
  3. If max line size is fixed I would use flexible array struct members:
#define LINE_LENGTH 255

typedef struct Text{
    size_t size;
    char lines[][LINE_LENGTH];
} Text;


Text *readFile(FILE *inputPtr, char *inputFileName, Text *textInFile) 
{
    char *linePtr = NULL;
    Text *tmp;
    do
    {
        size_t newsize = textInFile ? textInFile -> size + 1 : 1;
        tmp = realloc(textInFile, sizeof(*textInFile) + newsize * sizeof(textInFile -> lines[0]));  
        if(textInFile)
        {
            linePtr = fgets(tmp -> lines[newsize - 1], sizeof(tmp -> lines[0]), inputPtr);
            if(!linePtr) 
            {
                if(!textInFile)
                {
                    free(tmp);
                }
                else
                {
                    tmp = realloc(textInFile, sizeof(*textInFile) + (newsize - 1) * sizeof(textInFile -> lines[0]));
                    textInFile = tmp;
                }
                break;
            }
            textInFile = tmp;
            tmp -> size = newsize;
        }
    }while(tmp);
    return textInFile;
}
0___________
  • 60,014
  • 4
  • 34
  • 74