Home > Blockchain >  Double Linked List Dynamic Memory Allocation
Double Linked List Dynamic Memory Allocation

Time:05-22

I'm learning dynamic memory allocation and using doubly linked lists right now, and am not really understanding any of it. I want to keep a list of persons (which also has to be alphabetically sorted but I feel like that's still far away for me), but with using malloc and stuff.

struct person 
{
char name;
char adress;
int phone number; 
};

From main I'll access a func newPerson.

  1. Question: Now that I can't use an array struct person persons[50] anymore, how do I add a new person to my list? And what does my fgets line look like? Because fgets(persons['currentPosition'].name, 50, stdin) doesn't seem to be working

That's all for now, I've forgotten my other question...

CodePudding user response:

In order to add another person to your list, you need to do this way:

person * myperson = (person *) malloc(sizeof(person));

CodePudding user response:

I am using a linked list as an example but the process is the same for a double linked list.

#include <stdio.h>
#include <stdlib.h>

typedef struct list_node {
    void* value;
    struct list_node* next;
} list_node;

typedef struct person {
    char* name;
} person;

int main(void) {
    list_node* list = malloc(sizeof(*list));
    list->next = NULL;

    person* mike = malloc(sizeof(*mike));

    mike->name = malloc(20*sizeof(char));
    fgets(mike->name ,20 ,stdin);

    list->value = mike;

    printf(" Name : %s " ,((person*)list->value)->name);
    return 0;
}

You have to allocate memory for the person and then you have to allocate memory again for the person's name otherwise you will get segmentation fault.

  • Related