Help with Linked Lists!

0 Sha Kal · August 29, 2015
struct product{

    char* name;
    float price;

    struct product* next;  //
< Thing i can not understand

};


This struct product* next; is quite confusing to me, it is first time i see struct pointer inside of struct, or whatever. Any1 here can explain to me how exactly does that work and how does it store itself in memory, i would very much like to know, thanks.

Post a Reply

Replies

Oldest  Newest  Rating
0 c student · August 29, 2015
consider the following:

typedef struct node *link;

struct node {
   int value;
   link next;
};

here, link is defined as a pointer to a struct node.  a node has a value and it also has a pointer to another node.  let me abstract this and show you what it's like with a picture.

http://i.imgur.com/VfpgkpJ.png
as you can see, each node contains its two members.  link is a pointer to a node as shown with an arrow to represent it.  here is an example code:
typedef struct node *link;

struct node {
   int value;
   link next;
};

int main (void) {
   link node1 = malloc (sizeof (struct node));    // declare new node in heap
   node1->value = 1;      // arbitrary
   node1->next = NULL;    // IMPORTANT! Be careful of what this value is!
                          // currently points to nothing

   link node2 = malloc (sizeof (struct node));    // declare new node in heap
   node2->value = 2;      // arbitrary
   node2->next = NULL;    // IMPORTANT! Be careful of what this value is!
                          // currently points to nothing

   node1->next = node2;   // node1 points to node2
                          // since next is a pointer to node 2
                          // next is of type link (refer to image above)

   free (node2);          // free memory from heap
   free (node1);          // free memory from heap

   return 0;
}
  • 1

C

107,272 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator