I have spent several hours trying to initialize linked list with, say, integer values from 0 to 10. I create pointer of struct node and pass its reference to function init_ll. The init_ll function should initialize 10 elements of linked list. But it seems only first memory allocation works, because I get liked list with only one element.
#include <stdio.h>
#include <stdlib.h>
#define N 10
typedef struct node {
int value;
struct node *next;
} node_t;
void init_ll(node_t **head, int n)
{
// allocate memory for the first node
node_t *p= (node_t *)malloc(sizeof(node_t));
// copy the address of the first node to head
*head = p;
// initialize first node value
p->value = 0;
p = p->next;
// initialize the reamining nodes
for (int i=1; i<n; i++) {
p = (node_t *)malloc(sizeof(node_t));
p->value = i;
p= p->next;
}
p = NULL;
}
int main(void)
{
node_t *head;
init_ll(&head, 10);
return 0;
}
It seems I misunderstand some conception about memory-scope. I will be grateful if someone provide a proper example of allocation memory for linked list inside function. All I have found so far were examples of allocation of memory in main function.
p = p->next;
won't work well ifp->next
haven't been initialized (like in your case).node_t *p= (node_t *)malloc(sizeof(node_t));
->node_t *p= malloc(sizeof *p);
. It is both simpler and less error prone when refactoring.int i = 5; int j = i; j = 6;
isi
5 or 6?