VERY simple problem, can't figure it out for the life of me. :[
Ok, so all i'm trying to do is make a linked list of dictionary entries, and for some reason allocating the second or third linked list kills my program. I have no idea why. Here is the code:
header file:
Code:
#ifndef WORDSTAT_H
#define WORDSTAT_H
#define MAX_LINE 1024
/*define structure and functions*/
#define TS "?,.;\"': \n\t!()-<>[]{}1234567890"
struct wordEntry{
char *word;
int count;
struct wordEntry *next;
};
typedef struct wordEntry entry;
#endif
source file:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "template_wordstat.h"
void append(entry * beginning, char * nextWord);
int main(int argc, char* argv[])
{
FILE* fp;
char line[MAX_LINE];
int i = 0;
char *nextWord;
entry *start = NULL;
/* Checks for correct usage and handles arguments accordingly */
if (argc != 2) {
fprintf(stderr, "Error: wrong number of parameters.\n");
return -1;
}
if (strcmp(argv[1],"-h") == 0) {
printf("Usage: wordstat FILE_NAME\n");
return 0;
}
if ((fp=fopen(argv[1],"r")) == NULL) {
fprintf(stderr, "Error: cannot open file %s.\n", argv[1]);
return -2;
}
while (! feof(fp)) {
/* reads one line at a time */
if (fgets(line, MAX_LINE, fp) == NULL)
break;
if (line[0] == '\n') /* empty line */
continue;
/* extract words from the line and handle the words */
nextWord = strtok (line, TS);
/* if the first token is empty, then there are no words */
if(nextWord == NULL){
fprintf(stderr, "File contains no words.\n");
return -2;
}
/* go through each word and build linked list with entries*/
while(nextWord != NULL){
append(start, nextWord);
printf("%s\n", nextWord);
nextWord = strtok (NULL, TS);
}
}
/* sorting and printing */
fclose(fp);
return 0;
}
void append(entry * beginning, char * nextWord) {
entry *temp,*marker;
temp = (entry *)malloc(sizeof(entry));
strcpy(temp->word, nextWord);
temp -> count = 0;
temp -> next = NULL;
marker = beginning;
/* If the very first node is empty */
if (beginning == NULL) {
beginning = temp;
beginning -> next = NULL;
}
else {
while(marker -> next != NULL)
marker = marker -> next;
marker -> next = temp;
}
}
any help would be appreciated. I REALLy don't seem to get pointers :[
EDIT: I revised the code, it still doesn't work.