0

我正在尝试使用内存迭代地创建“节点”。我的代码目前只是说明了它的地址,实际上并没有尝试在链接列表中创建链接。

这是 a 的代码node

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
4

3 回答 3

3
cout << &new_etc << endl;

在这里,您正在打印变量的地址,即存储指针new_etc的内存位置,而不是它指向的地址。你想要的是:

cout << new_etc << endl;

您在哪里打印 的内容new_etcmalloc返回的地址。

现在,由于您free在每次迭代后都在使用此内存,因此您可能会获得不同的地址以及相同的地址 - 毕竟,如果您释放malloc了过去给您的内存,则意味着它可以被重用。

于 2013-05-23T13:42:35.447 回答
1

要打印指针的地址,请删除&

cout << &new_etc << endl;
        ^

它打印指针的地址new_etc,而不是指向的地址new_etc。的地址new_etc是相同的,并且在分配一个指针后不会改变。

编辑后的问题:查看显示不同地址的实时代码。因此,您的输出与您向我们展示的代码无关。

于 2013-05-23T13:43:20.980 回答
1
new_etc = (node*) malloc(sizeof(node));
...
free(new_etc);

如果您已经这样做了,为什么不应该malloc在下一轮返回相同的块?free它应该在缓存中很热,因此可能是最佳选择。

如果你没有free记忆,并且你修复了你的日志记录,会发生什么?

于 2013-05-23T13:45:47.333 回答