[英]I can alter a struct member from one location but not from the other
我試圖在C中實現一個鏈表-從簡單開始,一個列表包含一個節點。 但是,在嘗試將數據添加到節點時,我偶然發現了一些問題。 到目前為止,這是我的實現:
struct mylist_node {
int data;
};
struct mylist {
struct mylist_node *head_pt;
};
void mylist_init(struct mylist* l){
struct mylist_node head_node;
head_node.data = 5; //First try
l->head_pt = &head_node;
l->head_pt->data = 5; //Second try
};
而我的主要方法是:
int main()
{
struct mylist ml, *ml_pointer;
ml_pointer = &ml;
mylist_init(ml_pointer);
printf("%d\n", ml_pointer->head_pt->data);
ml_pointer->head_pt->data = 4;
printf("%d\n", ml_pointer->head_pt->data);
return 0;
}
這應該打印出來
5
4
如果我的指針知識是正確的。 但是,它打印出來
0
4
如您所見,我嘗試在mylist_init方法中兩次設置節點數據。 似乎都沒有作用-同時,從我的主要方法寫入和讀取它的效果很好。 我究竟做錯了什么?
在mylist_init
,您將局部變量的地址存儲在l
指向的結構中。 當函數返回時,該變量超出范圍,因此其占用的內存不再有效,因此以前指向該變量的指針現在指向無效位置。 返回局部變量的地址后,對該地址的取消引用會引發未定義的行為。
您的函數需要使用malloc
動態分配內存,因此當函數返回時,內存仍然有效。
void mylist_init(struct mylist* l){
struct mylist_node *head_node = malloc(sizeof(*head_node));
l->head_pt = head_node;
l->head_pt->data = 5;
};
另外,使用完內存后,請不要忘記free
內存。
對於初學者來說,您必須按照執行操作的方式為節點分配內存,節點是堆棧上的局部變量,函數退出后很可能會被覆蓋。
void mylist_init(struct mylist* l)
{
struct mylist_node *head_node = (struct mylist_node *)malloc(sizeof(struct mylist_node));
head_node.data = 5; //First try
l->head_pt = head_node;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.