Like so
Code:
#include <stdio.h>
//!! #include <malloc.h> malloc is in stdlib.h
#include <stdlib.h>
typedef struct DTNtag {
char data;
char* meaning;
struct DTNtag* otherLetter;
struct DTNtag* nextLevel;
} DictonaryTreeNode;
// use proper prototypes, not pre-ANSI K&R style
void print_words( DictonaryTreeNode *ptr);
int main(void) //!! yes, main returns an int
{
FILE *filein;
int ch;
DictonaryTreeNode *current, *DictionaryTreeNodePtr;
if ((filein = fopen("info.txt", "r")) == NULL)
{
fprintf(stderr, "ERROR: Cannot open input file. ");
exit(1);
}
//!! DictionaryTreeNodePtr = current = malloc(sizeof(DictonaryTreeNode) );
//!! start with an empty list
DictionaryTreeNodePtr = NULL;
current = NULL;
while ((ch=getc(filein)) != EOF)
{
printf("%c\n", ch);
current = malloc(sizeof(DictonaryTreeNode)); //!! allocate a new node
if ( current != NULL ) {
// fill in the data, and add to the list
current->data = ch;
current->nextLevel = NULL;
if ( DictionaryTreeNodePtr == NULL ) {
DictionaryTreeNodePtr = current; // first member of the list
} else {
DictonaryTreeNode *temp = DictionaryTreeNodePtr;
// find the end of the list
while ( temp->nextLevel != NULL ) {
temp = temp->nextLevel;
}
// append the new node to the list
temp->nextLevel = current;
}
}
else
{
fprintf(stderr, "Out of memory !\n");
return;
}
}
print_words(DictionaryTreeNodePtr);
fclose(filein);
return 0;
}
void print_words( DictonaryTreeNode *ptr)
{
while (ptr != NULL) {
printf("Words are %c.", ptr->data);
ptr = ptr->nextLevel;
}
printf("\n");
}
Couple of points
1. if you need malloc.h, then your compiler is really old and you should really consider upgrading to something which is ANSI compatible.
2. You don't need to cast the result of malloc in ANSI-C. If you think you do, check that you're not using a C++ compiler