How to initialize a linked list with a structure with many variables

I still have problems with the relationships between linked lists and structures.

See, my object should create a list in which each node contains 2 lines of characters. So, I tried something like this: first, I create a structure representing an element with my 2 char; secondly, the management structure for my list, thath will point to the top of my list. Which, in my .h, gives something like this:

typedef struct s_def { char *first_word; char *second_word; struct s-def *next; }  t_def

typedef struct s_type { t_def *first; } t_list;

Then I try to initialize my list. I create a function that works as follows:

t_list *list;
t_def *words;

list = malloc(sizeof(*list));
words = malloc(sizeof(*words));
if (list == 0 || words == 0)
   return (NULL);
words = NULL;
words->next = NULL;
list->first = words;

return (list);

Accuracy: I'm trying to make an empty list now, so the user can add some items later.

, : , . , , ! , : malloc , = NULL, , ,

words->next = NULL;

? NULL ?

+4
3

word

words = malloc(sizeof(*words));

3 NULL,

words = NULL;

, NULL:

words->next = NULL;

, words = NULL;

+5

, , :

words = NULL;
words->next = NULL;

words , , undefined.

+5

NULL, . → next - NULL- > next, . , , - :

typedef struct s_element
{
    char* firstWord;
    char* secondWord;
    s_element* next;
} t_element;


t_element* list = NULL;

t_element* addFront(t_element* list, char* word1, char* word2)
{
    t_element* next = list;
    list = malloc(sizeof(t_element));
    if (!list) return NULL;
    list->firstWord = word1;
    list->secondWord = word2;
    list->next = next;
    return list;
}

, - , , . , , , - malloc.

+1

Source: https://habr.com/ru/post/1614733/


All Articles