managing a list -newbie questions-
Hi everybody,
I'm trying to doan exercise from an old exam of a course I'm following..but I'm stuck with a segmentation fault (with the printf function) and well... I tried many times to modify the code but, so far, I only managed to get a few very strange errors and I really can't understand what's wrong with the functions. Any suggestion? Where am I wrong?
thank you!
Code:
#include<stdio.h>
#include<stdlib.h>
typedef struct elemento {
float valore;
struct elemento *next;
} Elemento;
typedef Elemento* List;
//Adds an element at the beginning
void Push(List *lista, Elemento e){
e.next=*lista;
*lista = &e;
}
//returns the value of the first element
float Read(List lista){
float pi=lista->valore;
return pi;
}
//counts the number of elements
int Count(List lista){
if(lista->next==NULL)
return 1;
int i;
List conta=malloc(sizeof(Elemento));
conta->next=lista->next;
for(i=1;(conta->next)!=NULL;conta=conta->next)
i++;
free(conta);
return i;
}
main(){
List a=malloc(sizeof(Elemento));
a->valore = 4.0;
a->next = NULL;
List prova=malloc(sizeof(Elemento));
prova->valore=2.0;
prova->next=NULL;
Push(&a,*prova);
float pi=Read(a);
printf("%f\n",pi);
printf("%d\n",Count(a));
}