[問題] C address返回後被改變了
開發平台(Platform): (Ex: Win10, Linux, ...)
WSL 2 Ubuntu 20.04 LTS
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
GCC 9.3.0
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
無
問題(Question):
老師出了個作業需要用到STACK(?)
想說用Linked List來實作
但是才剛寫到第一個function(pop)就卡關了
pointer指向的address在pop的最後
跟到pop外的不同
不知道發生了甚麼事
或者是我哪裡有理解錯誤
還麻煩大家幫忙一下
餵入的資料(Input):
無
預期的正確結果(Expected Output):
pHead before push = 0x559f50a342a0
pTail before push = 0x559f50a342a0
push(Tail):
pNode at the end of push = 0x559f50a346d0
pHead after push = 0x559f50a342a0
pTail after push = 0x559f50a342d0
↑
錯誤結果(Wrong Output):
pHead before push = 0x559f50a342a0
pTail before push = 0x559f50a342a0
push(Tail):
pNode at the end of push = 0x559f50a346d0
pHead after push = 0x559f50a342a0
pTail after push = 0x559f50a342a0
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
http://codepad.org/aUqamvdB
#include <stdio.h>
#include <stdlib.h>
struct Node{
struct Node* prev;
struct Node* next;
double data;
};
typedef struct Node Node;
void initial(Node* pNode){
static int i = 0;
pNode->prev = NULL;
pNode->next = NULL;
pNode->data = ++i;
}
void push(Node* pNode){
Node* pTemp = (Node*)malloc(sizeof(Node));
initial(pTemp);
pTemp->prev = pNode;
pNode->next = pTemp;
pNode = pNode->next;
pTemp = NULL;
printf("pNode at the end of push = %p\n\n",pNode);
}
int main(){
Node* pHead = (Node*)malloc(sizeof(Node));
Node* pTail;
initial(pHead);
pTail = pHead;
printf("pHead before push = %p\n", pHead);
printf("pTail before push = %p\n\n", pTail);
printf("push(pTail):\n");
push(pTail);
printf("pHead after push = %p\n", pHead);
printf("pTail after push = %p\n\n", pTail);
free(pHead->next);
free(pHead);
return 0;
}
補充說明(Supplement):
先謝過各位大大
腦袋打結中
先回寢室洗澡睡覺了
有任何回復可能中午後才會看到了
麻煩大家了
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.115.120.36 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1602369401.A.8D3.html
推
10/11 07:03,
3年前
, 1F
10/11 07:03, 1F
咦?
所以push裡面那樣寫沒有辦法更新到pTail...?
原本的pTail是指到pHead所指的記憶體位址
然後在push裡面
把pTail(pNode)的值更新成pTemp的值
所以這時候pTail不是指向pTemp所指的那個記憶體嗎?
麻煩大大解惑
※ 編輯: simon860730 (49.216.20.142 臺灣), 10/11/2020 07:31:52
→
10/11 08:15,
3年前
, 2F
10/11 08:15, 2F
→
10/11 08:15,
3年前
, 3F
10/11 08:15, 3F
了解了 剛剛改過可以了
非常感謝
推
10/11 12:47,
3年前
, 4F
10/11 12:47, 4F
→
10/11 12:47,
3年前
, 5F
10/11 12:47, 5F
好 我等等去看看
非常感謝
※ 編輯: simon860730 (49.216.20.142 臺灣), 10/11/2020 15:46:33
推
10/11 22:46,
3年前
, 6F
10/11 22:46, 6F