0

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?

2

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.