Jen
Jen

Reputation: 1338

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?

Upvotes: 0

Views: 64

Answers (2)

Ziffusion
Ziffusion

Reputation: 8943

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++;
}

Upvotes: 0

Andrea Martinelli
Andrea Martinelli

Reputation: 312

There are two valid options to do what you want:

1) use the realloc() function; it's like malloc and calloc but you can realloc your memory, as the name can advise;

2) use a linked list;

The second is more complex than the first one, but is also really valid. In your case, a simple linked list could have the form:

typdedef struct line
{ 
    int a;
    char *string;
    line *next;
    //line *prev;

} line;

Everytime you add a node, you have to alloc a struct line with your new data, set next pointer to NULL or to itself, it's the same, and set the previous next pointer to the new data you created. That's a simpy method to do manually a realloc. The prev pointer is needed only if you need to go from the last item to the first; if you don't need this feature, just save the root pointer (the first one) and use only next pointer.

Upvotes: 1

Related Questions