C: Can't link head and tail in double linked list with external function [addressing issue] -
i made simplification of double linked list. double linked list structure has head , tail nodes.
there function create list , return it. in same function linkage between tail , head nodes. problem when return list(so go outside function), links gone or point nodes of list temporarily created in function. guess correct? if how going bypass problem?
here's code:
#include <stdio.h> typedef struct node{ /*a node of list*/ int number; struct node *next; struct node *prev; } node; typedef struct list{ /*the list structure holds head , tail*/ node head; node tail; } list; list createlist(){ list newlist; newlist.head.prev=null; newlist.head.next=&newlist.tail; /*first node points second*/ newlist.tail.prev=&newlist.head; /*second node points first*/ newlist.tail.next=null; puts("--create list func--"); printf("head element address: %p\n", &newlist.head); printf("tail element address: %p\n", &newlist.tail); printf("head element points here: %p\n\n\n", newlist.head.next); return newlist; } int main(){ list numbers=createlist(); puts("--main func--"); printf("head element address: %p\n", &numbers.head); printf("tail element address: %p\n", &numbers.tail); printf("head element points here: %p\n", numbers.head.next); return 0; }
your guess correct; newlist
goes out of scope when function ends. function returns copy of list
object, pointer members still point @ original object.
you either need allocate list
on heap , return pointer (remembering free memory @ point), or take pointer-to-list
argument, , modify list
caller owns.
Comments
Post a Comment