Chained List

Asked

Viewed 52 times

-1

I’m having trouble understanding this struct pointer concept within the struct, how does it work? how endlessly stores the next element’s address?

typedef struct elemento Elemento;  
struct elemento  
{  
    int info;  
    Elemento* prox;  
};  

Elemento* lst_cria (void)  
{  
    return NULL;  
} 

Elemento* lst_insere (Elemento* lst, int val)  
{  
      Elemento* novo = (Elemento*) malloc(sizeof(Elemento));  
    novo->info = val;  
    novo->prox = lst;  
    return novo;  
}

2 answers

2

A pointer is nothing more than an address in memory.

When you declare a pointer in a struct, be it for the struct itself or anything else, until you assign some value to it, it’s just a random number (or 0, depending on the system/compiler/whatever, but don’t count on it).

So yes, in practice you can create addresses for the next elements infinitely (which is the point of the linked list, after all), it just doesn’t happen automatically (which I imagine is your concern). For every element you want to put in the list you need to allocate memory (the malloc there) and put this on the pointer on the last element you had.

TL;DR: No, the pointer does not generate an infinite struct. The pointer there is only a number.

0

You want to insert endlessly?

you can do what the friend above said, allocate memory as you did and put it into a repeat structure (with a condition to get out of it). Then you allocate a space every time and enter a value. When I did it in college, I created a menu with the options and put it inside a while, then every time I ran, I would allocate memory and I could insert it at will, until I chose the exit option. If not understand I try to explain better. Data structure is the terror of the crowd.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.