我正在尝试使用内存迭代创建“节点”。我的代码目前只是说明了它要去的地址,实际上并没有尝试在链表中建立链接。
这是节点
的代码:
struct node {
int num;
node *next;
};
这是 malloc()
的代码
node *etc = (node*) malloc(sizeof(node));
etc->num = 1;
etc->next = NULL;
cout << etc << endl;
for (int i=2; i<=10; i++) {
node *new_etc;
new_etc = (node*) malloc(sizeof(node));
cout << new_etc << endl;
}
编辑
输出:
0xcff010
0xcff030
0xcff050
0xcff070
0xcff090
0xcff0b0
0xcff0d0
0xcff0f0
0xcff110
0xcff130
最佳答案
cout << &new_etc << endl;
此处打印变量 new_etc
的地址,即存储指针 的内存位置,而不是它指向的地址。你想要的是:
cout << new_etc << endl;
打印 new_etc
的内容,即 malloc
返回的地址。
现在,由于您在每次迭代后释放
内存,您可能会获得不同的地址以及相同的地址 - 毕竟,如果您释放内存 malloc
过去给你的,就代表可以重用。
关于c++ malloc()不断分配给相同的内存地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16715501/