I have a singly-linked list. I am confident that I have the list set up and the data populated. However, when I go to print out the contents of the list, I'm not able to traverse it.
Code:
int main(int argc, char *argv[]) {
...
Neighbor *cursor, *root_ptr;
Neighbor this_neighbor;
// open the initialization file
if ((file = fopen(argv[5], "r")) == NULL) {
fprintf(stderr, "Failed to open file: %s\n", argv[5]);
time(&starttime);
exit(-1);
}
root_ptr = malloc(sizeof(Neighbor));
root_ptr->next = &this_neighbor; //keep a pointer to the root
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
char* p;
p = strtok(line, ",");
p++;
if (*p == *argv[1]) {
p = strtok(NULL, ",");
this_neighbor.send_to_using_port = atoi(p);
p = strtok(NULL, ",");
memcpy(this_neighbor.host, p, 1);
p = strtok(NULL, ",");
this_neighbor.neighbor_receives_on_port = atoi(p);
p = strtok(NULL, ",");
this_neighbor.link_cost = atoi(p);
fprintf(stdout, "host: %s\tsend on: %d\t receives on: %d\tcost: %d\n", this_neighbor.host, this_neighbor.send_to_using_port, this_neighbor.neighbor_receives_on_port, this_neighbor.link_cost);
Neighbor next_neighbor;
this_neighbor.next = &next_neighbor;
this_neighbor = next_neighbor;
}
this_neighbor.next = NULL;
}
// iterate over the lines in the file as a test
// THIS IS THE PART THAT ISN'T WORKING
cursor = malloc(sizeof(Neighbor));
cursor = root_ptr;
fprintf(stdout, "here\n");
fprintf(stdout, "%s\n", root_ptr->host); //<-- BLANK LINE
i = 1;
while (cursor != NULL) {
fprintf(stdout, "iteration number: %d\n", i);
fprintf(stdout, "%s\n", cursor->host);
cursor = cursor->next;
i++;
}
free (cursor);
...
return 0;
}
My output looks like this:
host: F send on: 6712 receives on: 7045 cost: 2
host: G send on: 6713 receives on: 7046 cost: 2
host: H send on: 6714 receives on: 7047 cost: 2
Send Receive Link
Neighbor Port on Port Cost
-------- ----- -------- ----
iteration number: 1
iteration number: 2
(blank line here)
So you can see that wherever I am trying to output a value from my list (were I am trying to iterate over it), I am getting a blank line. Further, the loop only iterates twice where it should iterate 3 times.
What am I doing wrong? Thanks!