链接列表中的指针地址未更改 [英] Pointer address does not change in a link list
本文介绍了链接列表中的指针地址未更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题是q->next
总是打印相同的地址,但是我分配了q = &x;
.为什么它不打印其他地址?
My problem is q->next
always prints the same address, but I assigned q = &x;
. Why it is not printing different addresses?
#include <stdio.h>
class Node
{
public:
int val;
Node *next;
Node(int v,Node *p) { val=v, next=p; }
};
int main()
{
Node head(0, NULL);
Node *q = &head;
int i = 5;
while (i>0)
{
Node x(i * 10, q);
q = &x;
printf("# %d %p\n", q->val, q->next);
i--;
}
}
推荐答案
这与x的分配方式有关:它是main函数内部的局部变量.这意味着它被分配在堆栈中的特定位置.您一直在重复使用同一块内存.相反,请尝试为新节点(new
)分配内存.
This has to do with the way x is allocated: It is a local variable inside the main function. That means it is allocated on the stack, at a specific position. You are reusing the same piece of memory all the time. Instead, try allocating memory for new nodes (new
).
这篇关于链接列表中的指针地址未更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文