trilobite
March 26th, 2011, 08:24 AM
Hi all -
I'm doing a simple linked-list in C.
The code is below. It compiles, but it simply prints out the number "42" four times, instead of printing 42, 5, 7, 10.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <malloc.h>
typedef struct node {
int val;
struct node *next;
} list;
list *add_val(list *l, int myint)
{
list *nl = malloc(sizeof(list));
l->next = nl;
nl->val = myint;
nl->next = NULL;
return nl;
}
int main(int argc, char *argv[])
{
list a;
a.val = 42;
a.next = NULL;
add_val(&a, 5);
add_val(&a, 7);
add_val(&a, 10);
int i;
for(i=0; i<4; i++)
{
printf("Value: %d \n", a.val );
}
return 0;
}
I'm not sure why the code isn't printing all of the values, so any help to fix this would be great. Many thanks in advance -
- trilobite
I'm doing a simple linked-list in C.
The code is below. It compiles, but it simply prints out the number "42" four times, instead of printing 42, 5, 7, 10.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <malloc.h>
typedef struct node {
int val;
struct node *next;
} list;
list *add_val(list *l, int myint)
{
list *nl = malloc(sizeof(list));
l->next = nl;
nl->val = myint;
nl->next = NULL;
return nl;
}
int main(int argc, char *argv[])
{
list a;
a.val = 42;
a.next = NULL;
add_val(&a, 5);
add_val(&a, 7);
add_val(&a, 10);
int i;
for(i=0; i<4; i++)
{
printf("Value: %d \n", a.val );
}
return 0;
}
I'm not sure why the code isn't printing all of the values, so any help to fix this would be great. Many thanks in advance -
- trilobite