Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

Initialize a linked list using ints in C

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

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

1 Reply

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...