Search code examples
carraysfilemultidimensional-arrayrealloc

How can I fully reallocate a 2D array in C?


Being concise, I want to read a file and store the content in a 2D array, where the first dimension refers to the line and the second dimension to the character in the respective line. I do not know the number of lines and columns on each line beforehand.

The code I tried is as follows.

P.S.: I know the variables's names are not that good XD

FILE *filepointer = fopen(commandlineargument.filtersfile, "r");
int numboflines = 0;
int numbofchars = 0;
char **array = malloc(numboflines + 1);
array[0] = malloc(numbofchars + 1);
char currentchar; 
while(fscanf(filepointer, "%c", &currentchar) != EOF)
{
    if(currentchar != '\n')
    {
        array[numboflines][numbofchars] = currentchar;
        numbofchars++;
        array[numboflines] = realloc(array[numboflines], numbofchars + 1);
    }
    else
    {
        array[numboflines][numbofchars] = '\0';
        numbofchars = 0;
        numboflines++;
        array = realloc(array,  numboflines + 1);
    }
}
array[numboflines] = '\0';
numboflines--;

With the code above, I can just get the value of array[0][0] and only before it gets reallocated two lines down (then array[0][0] points to null). I get Segmentation Fault later.

P.S.: I know the code above will only work properly if the last line ends with a \n

An example of the desired output:

File Content:

>Abcde
fghijk
>Lmno
pq

2D Array values:

array[0][0] = ">"
array[2][1] = "L"

And so on.


Solution

  • Your code is fine, but it has one omission and one mistake:

    The mistake: memory space for each element of array is not a character, but a pointer to a character, so this line:

    char **array = malloc(numboflines + 1);
    

    should be rewritten as this:

    char **array = malloc((numboflines + 1)*(sizeof *array));
    

    The omission: after you end a line and realloc array, you must malloc the newly array element:

    numboflines++;
    array = realloc(array,  numboflines + 1);
    

    Becomes:

    numboflines++;
    array = realloc(array,  (numboflines + 1)*(sizeof *array));
    array[numboflines] = malloc(numbofchars + 1);