user98967885655
user98967885655

Reputation: 1

How to dynamically create multiple instances of struct in loop in C?

I have the following code to create one-way list of user-specified number of elements

typedef struct Node{
    int val;
    struct * Node next;
} Node;

int main(){
    int num;
    Node * prev = NULL;
    Node * first = NULL;
    while(scanf("%d", num) != EOF){
        Node node;
        node.val = num;
        if(prev == NULL){
            prev->next = &node;}
        prev = &node;
        if(first == NULL){
            first = &node;}
    }
}

but this seems to create 1 node and edit it each iteration

as far as I understand new() exists only in c++, is there any way to do this without making array via malloc() and reallocating it every iteration?

Upvotes: 0

Views: 91

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

Your code is invalid and results in undefined behavior.

For example if the pointer prev is a null pointer then you may not dereference it as you are doing in this if statement

    if(prev == NULL){
        prev->next = &node;}

Moreover this declaration

Node node;

is alive only in each iteration of the while loop. So pointers that point to the object node will not be valid after the while loop.

And this call of scanf

scanf("%d", num)

is invalid. Instead you shall write

scanf("%d", &num)

How to dynamically create multiple instances of struct in loop in C?

It seems you want something like the following.

Node *head = NULL;

int num;
for ( Node **current = &head; 
      scanf("%d", &num) == 1 && ( *current = malloc( sizeof( Node ) ) ) != NULL;
      current = &( *current )->next )
{
    ( *current )->val = num;
    ( *current )->next = NULL;
}

To free all the allocated nodes when the list will not be required any more you can write the following while loop

while ( head != NULL )
{
    Node *tmp = head;
    head = tmp->next;
    free( tmp );
}

Upvotes: 0

Kaze
Kaze

Reputation: 11

Think about the scope. When you use a while loop in your program, a pair of curly braces is used. It means that your newly created node can only survive between the curly breaces. Every time the loop body is carried out, the memory will be recycled. Note that when you get in the loop body, the system allocate the memory from stack, which will be recycled. But malloc() will allocate from the heap, which need to be managed by your self. So malloc() can continuously gives you a new node. Hope it's helpful! :)

Upvotes: 0

Related Questions