Search code examples
carraysstructmallocrealloc

Allocating array of struct with array inside


I want to read users input combined of strings and numbers, like this:

50:string one
25:string two blablabla
...

I don't know how many of the lines the input will have and I also don't know maximum length of the strings.

So I created

typdedef struct line
{ 
    int a
    char *string
} line;

Then an array of this sturct

line *Array = NULL;

Now I have a cycle, that reads one line and parses it to temporaryString and temporaryA. How can I realloc the Array to copy these into the array?


Solution

  • You could something like this (pseudo code).

    idx = 0;
    
    while (input = read()) {
        temporaryString, temporaryA = parse(input);
        Array = realloc(Array, (idx + 1)*sizeof(line));
        Array[idx].a = temporaryA;
        Array[idx].string = malloc(strlen(temporaryString) + 1);
        strcpy(Array[idx].string, temporaryString);
        idx++;
    }