我正在嘗試實作一個鏈表并向其中添加節點。n
我遇到了以下問題,當我設定list->next
指向相同地址后嘗試釋放指標時,再次列印時第二個節點內n
的int
值也變為垃圾值。我想知道是否在記憶體中,n
并list->next
存盤為兩個單獨的指標,它們持有相同的值,還是存盤為單個指標?如果它們是不同的,那么為什么釋放n
也會影響list->next
?此外,如果釋放n
使第二個節點丟失,那么為什么我仍然可以使用list->next->next
指標添加第三個節點,是list->next->next
指標還有一些指向隨機可用位置的隨機值?這是我的代碼,對不起,如果我的問題太模糊,我正在盡力理解所有這些指標。
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
typedef struct node {
int number;
struct node *next;
} node;
int main(void) {
node a;
a.number = 1;
a.next = NULL;
node *list = NULL;
list = &a; // the first node
printf("%i \n", a.number);
node *n = malloc(sizeof(node)); // creating pointer to the second node
if (n != NULL) {
n->number = 2;
n->next = NULL;
}
list->next = n; // add the node to the list
printf("%p \n%p \n", n, list->next); // print out the address and value
printf("%i \n", list->next->number);
free(n);
printf("%p \n%p \n", n, list->next); // print out the address and value
printf("%i \n", list->next->number);
n = malloc(sizeof(node));
printf("%p \n%p \n", n, list->next);
if (n != NULL) {
n->number = 3;
n->next = NULL;
}
list->next->next = n;
printf("%i\n", (*(*(*list).next).next).number);
return 0;
}
這是輸出
1
0x5562319d62a0
0x5562319d62a0
2
0x5562319d62a0
0x5562319d62a0
1445140950
0x5562319d62a0
0x5562319d62a0
3
uj5u.com熱心網友回復:
那作業
list->next = n
不復制分配的記憶體。它只是添加另一個指向同一記憶體的指標。
如果我們“繪制”它,在賦值之前它看起來像這樣:
--- ----------------- | n | ---> | 節點記憶體 | --- -----------------
然后在分配后你有:
--- | n | ------------\ --- | ----------------- >--> | 節點記憶體 | ------------ | ----------------- | 串列->下一個 | --/ ------------
然后你通過n
導致free
這種情況:
--- | n | ------------\ --- | >--> ??? ------------ | | 串列->下一個 | --/ ------------
呼叫后free
,指標list->next
無效。任何取消參考它的嘗試都會導致未定義的行為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/506450.html
上一篇:C中的字串文字真的不可修改嗎?