user793384
user793384

Reputation: 73

how to properly create a linked list

// creating a struct to store number of cd's, titles, and count
struct CD_type_node
{
    int cd_number;
    char title[20];
    int count;
    struct CD_type_node* next;
};

struct CD_type_node* mylist = NULL; // declaring a struct of type CD_type_node
struct CD_type_node* header;// head pointer for accessing linked list
header = NULL;

header = malloc(sizeof(struct mylist));
header = mylist;

while(header != NULL)
{
    header = header->next;
}

can someone tell me how to properly create a linked list and how to allocate memory dynamically because im getting an error: "invalid application of "sizeof" to incomplete struct mylist

Upvotes: 1

Views: 700

Answers (3)

Patrick87
Patrick87

Reputation: 28332

You need to use sizeof(struct CD_type_node).

Upvotes: 2

David Heffernan
David Heffernan

Reputation: 613612

I'd extract the node creation into a function of this sort of form:

void AddNode(struct CD_type_node **head)
{
    struct CD_type_node *newNode = malloc(sizeof(struct CD_type_node));
    newNode->next = *head;
    *head = newNode;
}

For convenience you would probably want to pass in the other fields in the struct and get this routine to fill out the new node with those values. But this routine gives you the idea of how to do the allocation and next pointer code.

Upvotes: 2

Your problem is here

header = malloc(sizeof(struct mylist));

because mylist is a variable with type struct CD_type_node*, so

header = malloc(sizeof(*mylist));

is fine as is

header = malloc(sizeof(struct CD_type_node));

but struct mylist is wrong: it doesn't name either a type or a variable from which a type can be extracted.

Upvotes: 3

Related Questions