Reputation: 83
The program does not print the list's values as it is intended to. It prints something that's gotta be a memory address imo. I've been trying to find the solution solo, but to no avail thus far. I would appreciate some help.
#include <stdio.h>
typedef struct node
{
int val;
struct node * next;
} node_t;
void print_list(node_t * head);
void main()
{
node_t * head = NULL;
head = malloc(sizeof(node_t));
if (head == NULL)
return 1;
head->val = 1;
head->next = malloc(sizeof(node_t));
head->next->val = 2;
head->next->next = malloc(sizeof(node_t));
head->next->next->val = 3;
head->next->next->next = malloc(sizeof(node_t));
head->next->next->next->val = 18;
head->next->next->next->next = NULL;
print_list(&head);
system("pause");
}
void print_list(node_t * head) {
node_t * current = head;
while (current != NULL) {
printf("%d\n", current->val);
current = current->next;
}
}
The aforementioned problem was resolved thanks to your inputs. Thank you very much! However, a new issue occurred. Wanting to add a new element to the list, I added a few lines of code. Unfortunately, the wanted result is not printed and the program is terminated abruptly. Here's the new code:
head->next->next->next->next = malloc(sizeof(node_t));
head->next->next->next->next->val = 5556;
head->next->next->next->next->next = NULL;
node_t * current = head;
while (current->next != NULL)
{
current = current->next;
}
current->next = malloc(sizeof(node_t));
current->next->val = 32;
current->next->next = NULL;
printf("%d\n", current->next->val);
system("pause");
}
Upvotes: 0
Views: 2626
Reputation: 11
Your print_list
function is called using print_list(&head);
, however head is already a pointer to a node.
This means that the print_list function is actually receiving a pointer to a pointer to a node, or node_t **
. As such, when you try to print the values of the pointer you will see something that appears to be a memory address. To fix this, just pass in the head of the list using print_list(head);
Upvotes: 0
Reputation: 798
Change your print_list(&head)
function to print_list(head)
.
print_list(&head);
to
print_list(head);
function void print_list(node_t * head)
accepts single reference pointer. But your passing **head
to the print_list
function.
Upvotes: 0
Reputation: 689
Note that your function void print_list(node_t * head);
expects a parameter of type node_t *
but you are passing parameter of type node_t **
.
Change print_list(&head);
to print_list(head);
head
is of type node_t *
while &head
is of type node_t **
.
Upvotes: 5