Reputation: 63
Following is the part of a code which wrote for making a linked list
struct node
{ int data;
struct node *link;
}*head;
In the above source code, I want to ask that whether head is a variable of "node" or not. I think that as I declared it with structure so it must be a variable to the defined structure & thus contain a data part & a address part. If I am wrong can anyone please tell me what is the role of *head & is it a variable or not ?
Now , this is the second part of the same source code
void addbeg()
{
int d,g;
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
}
Here void addbeg
is a function, now here we declared another variable to struct node
, then why are we allocating it memory equal to a int
, as it is a variable to struct node, so it must contain size of a pointer & a int
. But why are still allocating it memory. Please clear this doubt also.
Upvotes: 0
Views: 69
Reputation: 957
I'll try to explain your questions in brief, but to solve your confusion, @ForceBru's comment is the right idea.
The usage of struct
in C
, defining variable right after the definition of a struct
is a short cut to do those two steps separately, namely it equals to define the struct
+ struct node *head
(define a variable pointing to a struct node / a pointer to node).
temp
as a pointer to a struct node is similar to variable node
, except that it's now pointing to a real struct node that have been just allocated in memory space (using malloc
). It's similar to the following code, but differ in whether the compiler or yourself should manage the memory allocated (due to dynamic memory allocation).
// define a struct node that's allocated and managed by the compiler
struct node nodeOfTemp;
struct node *temp = &nodeOfTemp;
Upvotes: 1