Hi C wizards,
I am working on a demographic simulation model where I have a population of individual people represented as structs:
The data to populate the model is read in from a csv file and the individuals are added to one of three linked lists based on their age: child, adult, and elderly. The lists are sorted in descending order so that the oldest person in the group is the head node and the youngest person is always the tail node.Code:struct person { int age; struct person *next_node; };
On each day of the simulation, the age of each person is incremented and when a threshold age is reached, the individual needs to be transferred into the next group. For example, this is the code snippet that transfers a child to the adult list. The function add_person_to_list() inserts the node based on age, which in this particular case, will always be at the end of the list.
The problem I am running into is setting the "next_node" pointer to NULL when the node is transferred to the new list. The way my current code is set up, the pointer for "prev_node -> next_node" is also changed to NULL and the while loop terminates without reading through the end of the child list.Code:int threshold = 7000; struct person *prev_node; struct person *current_node; prev_node = child; current_node = child; while(current_node != NULL) { if(current_node -> age < threshold) { current_node -> age = (current_node -> age) + 1; prev_node = current_node; current_node = current_node -> next_node; } else { current_node -> age = (current_node -> age) + 1; child = current_node -> next_node; prev_node -> next_node = current_node -> next_node; current_node -> next_node = NULL; /* PROBLEM LINE !!!*/ adult = add_person_to_list(current_node, adult); current_node = prev_node -> next_node; /* ALSO BECOMES NULL */ } }
I tried creating a dummy pointer and having 'next_node' point at that instead, but it doesn't seem to work.
I also tried copying the node before transfer. This works, but it seems like a recipe for massive memory leaks.Code:struct person *dummy_ptr = NULL; current_node -> next_node = dummy_ptr;
I am probably missing something intuitive about pointers and memory. What method would you guys suggest?Code:struct person *copy_node( struct person *original_node) { struct person *new_node = (struct person*)malloc(sizeof( struct person )); new_node -> age = original_node -> age; new_node -> next_node = NULL; return(new_node); } current_node -> age = (current_node -> age) + 1; child = current_node -> next_node; prev_node -> next_node = current_node -> next_node; new_node = copy_node(current_node); adult = add_person_to_list(new_node, adult); current_node = prev_node -> next_node; }
The real simulation model is a lot more complex in terms of the decisions and individuals that have to be transferred. Hopefully this is enough information for you to understand my problem. Thanks in advance for your help.



LinkBack URL
About LinkBacks


