I was trying to create a single linked list in C, unfortunately something goes wrong. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int size,i;
struct list
{
int val;
struct list *next;
};
typedef struct list element;
void add(element *head, int value)
{
element *current;
current = (element*) malloc(sizeof(element));
current->val = value;
current->next = head;
head = current;
}
void displayList(element *first)
{
element *curr = first;
while (curr != NULL)
{
printf("%d",curr->val);
curr = curr->next;
}
}
int main()
{
element *head, *curr;
head = NULL;
/* This works fine, although I would like to insert this into a function add
curr = (element*) malloc(sizeof(element));
curr->val = 65;
curr->next = head;
head = curr;
*/
add(head, 15); ////Function add doesn't work, although the code is same as above
displayList(head);
}
For now I would just like to add a single number to the list just to see if it works using add function. The commented part works fine and program returns '65' until I put it in the function. When I try to use add function the result is "Process returned 0 (0x0)" and nothing more. I suppose there's something wrong with passing the list's head to add function, but I can't find any mistake.
gcc -Wall -g). Then, use the debugger (e.g.gdb)element **headRefso that it can be modified in the function