
newbie question: returning structs from functions
Quote:
> i am having trouble with a function that i created. i have
> created a priority queue and functions to use with the
> priority queue and this function is giving me trouble. when
> debugging this it seems that everything is ok before the
> function returns, but after it returns the queue is broken
> and not logically in order. is it because i declared a node
> of my queue inside the function and then return it. should i
> return a pointer instead.
You haven't provided enough context, but your code seems a little
strange.
Quote:
> struct myNode removeHighestPriorityNode(){
> struct myNode nodeA; //declare temporary node
> nodeA = *(head.next); //nodeA set to node with
> highest priority head.next = nodeA.next; //give
> nodeA.next highest priority in queue nodeA.next = NULL;
> //detach nodeA from queue return(nodeA);
> }
Oops! //-comments do not wrap very well. Better to use C comments.
Let's reformat the code.
Quote:
> struct myNode removeHighestPriorityNode(){
This is a function which returns a struct by value.
Quote:
> struct myNode nodeA; /*declare temporary node */
> nodeA = *(head.next); /*nodeA set to node with highest
priority */
head.next obviously points to a struct myNode, which is copied and
assigned to nodeA.
Quote:
> head.next = nodeA.next;/*give nodeA.next highest priority in
queue */
Now it seems like nothing points to the struct previously pointed
to by head.next. Possible memory leak.
Quote:
> nodeA.next = NULL; /*detach nodeA from queue */
> return(nodeA);
> }
A copy of the highest priority node is returned. You should
probably return a pointer to the node instead.
This was the best I could do with the amount of information you
gave. If my post seems incomprehensible, please post some more of
your code, like the definition of struct myNode and the global
variable head.
--
Stockholm, Sweden