2016-05-01 8 views
0

何が起こっているのか誰にでも説明できますか? このコードは正常に動作します:C構造体から別の関数にリストを渡す

#include <stdio.h> 
#include <stdlib.h> 

typedef struct def_List List; 

struct def_List { 
    int x; 
    int y; 
    List *next; 
}; 

typedef struct def_Figures { 
    List *one; 
    List *two; 
} Figures; 

void another_function(List *l) { 
    l = (List*) malloc(sizeof(List)); 
    l->x = 1; 
    l->next = NULL; 
} 

void function(Figures *figures) { 
    another_function(figures->one); 
} 

int main() { 
    Figures ms; 
    function(&ms); 
    printf("%d",ms.one->x); 
    return 0; 
} 

印刷 "1"

#include <stdio.h> 
#include <stdlib.h> 

typedef struct def_List List; 

struct def_List { 
    int x; 
    int y; 
    List *next; 
}; 

typedef struct def_Figures { 
    List *one; 
    List *two; 
    List *three; 
} Figures; 

void another_function(List *l) { 
    l = (List*) malloc(sizeof(List)); 
    l->x = 1; 
    l->next = NULL; 
} 

void function(Figures *figures) { 
    another_function(figures->one); 
} 

int main() { 
    Figures ms; 
    function(&ms); 
    printf("%d",ms.one->x); // 1 
    return 0; 
} 

版画 "-1992206527": 私は3番目のリストを追加します。

これは1つまたは2つのリストでうまくいきますが、3つ以上のリストを追加すると、何かがうまくいかなくなります。どうして?

+1

どちらも**未定義の動作**です。 'l =(List *)malloc(sizeof(List));'呼び出し側変数を更新しません。 – BLUEPIXY

答えて

0

あなたはanother_function(List *l)の引数変更しようとしている。

l = (List*) malloc(sizeof(List)); 

代わりにポインタへのポインタを使用します。

void another_function(List **l) { 
    *l = (List*) malloc(sizeof(List)); 
    ... 
void function(Figures *figures) { 
    another_function(&figures->one); 
}  

を注意してください:

Figures ms; 
function(&ms); 

を図構造体MSながらリストが1つ、2つ、3つがNULLで、どこでも指していません。

+0

ありがとうございました!今それは動作します。 another_function(figures-> one)を渡した後、figures-> oneがリストへのポインタである場合、別の関数の中でそれを更新することができると思いました。 – smutnyjoe

関連する問題