kapil
kapil

Reputation: 624

difference between structure pointer and member of structure pointer

I am declaring a structure here

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

I am creating a pointer with this declaration

struct node *link;

Is there any difference between next and link pointer or are they the same type of pointer?

Upvotes: 1

Views: 1851

Answers (3)

amit
amit

Reputation: 1

struct node
{
  int data;
  struct node *next; // line 1
};

struct node *link; // line 2

line 1 is known as self referential structure and line 2 is just a pointer variable of given structure. In linked list self referential structure is used, because we want all the nodes of same type. Suppose, if you declare struct node *p = malloc(sizeof (node)); Here, p creates some space and that space is divided in two parts 1. int data 2. *next . means one portion has data and other portion has address of next node.

Upvotes: 0

Pandrei
Pandrei

Reputation: 4951

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

struct node *link

*next and *link are both pointers, so their size will be the same. The data type they point to is the same, the structure node. But they are quite different:

struct node *p = malloc(sizeof (node)); //allocate memory for a new node

//now, p will point to an address.
//p->next is still un-initilized, so we have to assign it an address 

p->next = NULL; 

p, and p->next point to different addressess

So the two pointers are different and exist independently of each other. In fact, *link does not even have to be a pointer, you can statically allocate memory for a node:

struct node p;
p.next=NULL

Or you can add other pointers to node to the node structure for more complex data structures like trees or double linked lists:

struct node
{
   int data;
   struct node* next;
   struct node* prev;
}

Upvotes: 0

Sumeet
Sumeet

Reputation: 8292

There is one difference.

The link pointer can have an initial value but next pointer cannot have an initial value and the reason is:

Whenever we declare a structure,we are declaring a new type and not a new variable.

So

struct node *link=NULL;

is allowed while

struct node
{
  int data;
  struct node *next=NULL;
};

is NOT allowed.

Upvotes: 1

Related Questions