1

I'm probably missing something pretty simple again but too many hours in the lab have left me unable to see what I did wrong here. I'm attempting to build a linked list of all the characters being read in from a file by creating a list and appending new nodes to it as new characters are read in until the end of file.

First some background, here's the code for the node structure:

typedef struct node
{
//each node holds a single character
char data;
//pointer to the next node in the list
struct node *next;
}node;

Through the use of a couple of printf statements I've managed to narrow the issue down to somewhere in this block of code.

FILE *infile = fopen("data.txt", "r");

int c;
int counter = 0;
node *head, *current = NULL;

//Get the count of our original rules and create the list
do{

   node *item = new node();

  c = fgetc(infile);      

  if(c == '\n'){
counter ++;
  }

  printf("From infile: %c \n", c);

item->data = c; 
item->next = NULL;

printf("Item data: %c", item->data);

if (head == NULL){
  head  = current =  item;
}
else {    
  current->next = item;
  current = item;
}

}while( c != EOF);

I'm not certain where it is but I know it's in there. If i could just get another pair of eyes to point out where this is going wrong I'd appreciate it.

1 Answer 1

3

You do not intialize head here:

node *head, *current = NULL;

so it will have an indeterminate value, so most likely this check is failing:

if (head == NULL){

and therefore neither head nor current would be properly initialized.

If you are using C++11 then you should be using nullptr instead of NULL.

Sign up to request clarification or add additional context in comments.

3 Comments

this is c++ ideally we should be using nullptr
@Mgetz Ideally, we shouldn't be using fgetc, printf, FILE*, naked pointers and redundant structs as well ;)
That's got it! Thanks! Whew, if I missed that it might be time for a little break.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.