Question:
Return c Linked List from Function?
anonymous
2016-04-07 23:06:33 UTC
Hi Everyone,

I guess I am a little confused with pointers and I need your help. So, I have a function that should return a pointer. However, should I create the linked list head node outside the function or inside the function -- because I know that memory allocated locally are destructed when the function ends? Also, when I create a linked list inside the function, how do I return the head node?


Thanks!
Three answers:
carmon
2016-04-09 22:46:17 UTC
When you use the new operator to allocate memory, this memory is assigned from the heap. Memory from the heap remains allocated until explicitly deallocated.



If you do this in a function, the pointer value you receive will usually be assigned to a local variable. If that pointer value is the return value of the function, then the calling routine gets that value (and presumably saves it), but the local variable (which was on the stack) is destroyed, but that shouldn't matter.



#include



using namespace std;



struct node

int x;

node *next;

;



node* genRootNode (int i)

node *root;

root = new node;

root->next = 0;

root->x = i;

return root;







int main()

node *nodeRoot = genRootNode (5);

cout << nodeRoot->x;
Robert J
2016-04-08 00:30:20 UTC
If it's a small amount of storage, you could declare it as static within your function and return a pointer to it.



Static storage is retained outside / between function calls.



Or use malloc() to obtain blocks of system memory - but be careful to de-allocate (free) memory if you unlink any block from your list structure; otherwise the memory use will just keep increasing, a "memory leak".



With that I would declare the root node pointer as static or global, so it cannot be lost.



http://www.cprogrammingexpert.com/C/Tutorial/dynamic_memmory_allocation/malloc.aspx
anonymous
2016-04-08 08:28:12 UTC
Start with the empty liked list structure. Pass a pointer to this to the function.

struct LinkedList;

makeLinkedList(&LinkedList);



void makeLinkedList(struct LinkedList* pll)

{

pll->head = /* use malloc for the head type */

/* etc*/

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...