Reputation: 193
typedef struct node{
int data;
struct node* next;
}ListNode;
void init(ListNode **head){
(*head) = (ListNode *)malloc(sizeof(ListNode));
(*head)->next = 0;
}
ListNode* another_init(){
ListNode *head = (ListNode *)malloc(sizeof(ListNode));
return head;
}
I have some problems:
1.in function init,why should I put a second rank pointer ?
2.Is function init the same with another_init ?
Upvotes: 0
Views: 104
Reputation: 2857
2.Is function init the same with another_init ?
In case you use malloc
they are not equal If you use calloc
,they will be equal.
1.in function init,why should I put a second rank pointer ?
If you insist on malloc . You should set the next
to 0
.
Or you will face bugs sometime. Thinks this:
Maybe you have a print_link function:
void print_link(struct node * head)
{
node * now = head;
while(now != NULL)
{
print_some_data_you_want;
now = now->next;
}
}
And if you just call this function after use the second init function. You never know what will happened.
Upvotes: 0
Reputation: 613
another_init is not "the same as" init. It doesn't set the next-pointer to 0. From malloc(3): malloc() allocates size bytes and returns a pointer to the allocated memory. The memory is not cleared.
Upvotes: 1