Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to initialize a linked list using ints given from the main.c.

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

int main(int argc, char ** argv) 
{
     int b = 128;
     int M = b * 11;  // so we have space for 11 items

     char buf [1024];
     memset (buf, 1, 1024);     // set each byte to 1

     char * msg = "a sample message";

     Init (M,b); // initialize

I know what I have isn't correct, but it's the best I could come up with.

#include <stdio.h>
#include "linked_list.h"

struct node
{
     int value;
     struct node *next;
};

struct node* head;
struct node* tail;

void    Init (int M, int b)
{
     head = (struct node *) malloc(sizeof *head);
     tail = (struct node *) malloc(sizeof *tail);
     head->next = tail;
     tail->next = tail;
} 

I just cannot see how to initialize the linked list using the ints. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
126 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your list is described by a pointer to its head element.

Now you want to initialise the list so that it is usable. The default state is an empty list, i.e. one that does not have any nodes. So what you don't do is to allocate memory. Just do this:

struct node *head = NULL;

You have a NULL head, which means that you don't have any elements. When you add nodes, you create them with malloc and assign them via this pointer. If the head is NULL, it must be updated to point to the first node, whose next member must be NULL.

Remember: Most pointers just point to existing data. There's no need to allocate memory to such pointers. And make sure to always initialise pointers properly; they should either point to valid memory or be NULL to mean "not pointing to anything".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...