2011-02-09 10 views
0

私は二重リンクリストを単純化しました。私の二重リンクリストは、ノードとして頭と尾を持つ構造です。C:二重リンクリストの頭と尾を外部関数とリンクできません[アドレス指定問題]

リストを作成して返す機能があります。同じ機能では、私は尾と頭のノードの間のリンケージを行います。問題は、リストを返す(関数の外に出る)とき、すべてのリンクがなくなったか、関数内で一時的に作成されたリストのノードを指しているということです。私の推測は正しいですか?もしそうなら、私はどのようにこの問題を回避するつもりですか?

#include <stdio.h> 

typedef struct node{  /*a node of a list*/ 
    int number; 
    struct node *next; 
    struct node *prev; 
} node; 

typedef struct list{ /*the list structure that holds only the head and tail*/ 
    node head; 
    node tail; 
} list; 

list createList(){ 
    list newList; 
    newList.head.prev=NULL; 
    newList.head.next=&newList.tail; /*first node points to the second*/ 
    newList.tail.prev=&newList.head; /*second node points to the 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; 
} 

答えて

0

あなたは値によって新たに作成されたリスト項目を返すことができないため、動的なメモリ割り当て(malloc()free())を使用する必要があります。

は、ここでは、コードです。

+0

可能です。問題はコンパイラが浅いコピーのみを実行することです。 –

+0

@Oliいいえ、この場合は、変数のアドレスが変更されるためできません。 –

+0

はい、それは浅いコピーのために問題です! –

1

あなたの推測は正しいです。関数が終了すると、newListが範囲外になります。この関数はlistオブジェクトのコピーを返しますが、ポインタメンバーは依然としてオリジナルのオブジェクトを指します。

あなたはどちらかは、ヒープ上listを割り当て、(いくつかの点でメモリを解放するために覚えている)ポインタで返す、または引数としてポインタ・ツー・listを取り、呼び出し側が所有していることをlistを変更する必要があります。

0

あなたの関数内にlist newlistという名前のリストを作成することはできません。リストへのポインタを返す必要があります。スタック上の変数は、関数が返ってもそこに存在することは保証されていません。

list* createList(){ 
    list* newList = (list*)malloc(sizeof(list)); 
    newList->head.prev=NULL; 
    newList->head.next=newList->tail; /*first node points to the second*/ 
    newList->tail.prev=newList->head; /*second node points to the 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; 
} 
+0

これはCではないC++です。一定。 –

関連する問題