Hi, I'm new to the forum and have been trying to learn about dynamically linked lists. I'm having a problem with my code, adding nodes to a list seems to work but for some reason I can't manage to print (or to free memory for that matter). My thought is that there's something wrong with my pointers, but I can't put a finger on what and where I am going wrong.
My guess is that there's a simple fix with pointers...
Here's what I have gotten so far...
Code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE_MAX 20
#define BUFFER_MAX 256
FILE *file;
/*Stuct*/
struct car {
char name[SIZE_MAX];
int year;
struct car *next;
};
typedef struct car Car;
int addToList(Car *head, char *, int);
void printList(Car *head);
void releaseMem(Car *head);
/*functions*/
int addToList(Car *head, char *name, int year ){
struct car *nd;
nd = malloc(sizeof(struct Car));
strcpy(nd->name, name);
nd->year = year;
//printf("%s %d\n",nd->name,nd->year);
nd->next = NULL;
if (head!=NULL){
head->next = nd;
}
return 1;
}
void printList(Car *head){
Car * current;
current = head;;
while (current!=NULL){
printf("%s %d\n",current->name,current->year);
current = current->next;
}
}
void releaseMem(Car *head){
Car * current = head;
while (current != NULL) {
//printf("remove %s %d",current->name ,current->year);
free(current);
current = current->next;
}
printf("Mem free'd.\n");
}
/*Main*/
int main (int argc, char *argv[]){
Car *head = NULL;
int year = 100 ;
char buffer [BUFFER_MAX];
char name[SIZE_MAX];
/*opening file*/
file = fopen(argv[1], "r");
if (file == NULL){
printf("\n\tWARNING: No data found.\n");
exit(1);
}
else{
printf("Reading file %s. \n",argv[1]);
}
printf("Data read to list.\n");
while(fgets(buffer, BUFFER_MAX,file)!= NULL){
sscanf(buffer,"%s%d",name,&year);
//printf("%s %d\n",string, year);
addToList(head,name,year);
}
printList(head);
releaseMem(head);
return 0;
}