C语言 指针副本报告不同的值



我正在使用c.创建游戏的道具系统。

我想用头存储项目数组的地址,当这个程序运行时,header将返回相应的地址。

我的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
struct Header{
struct ItmInfo *itmAddress;
// a pointer that store the address of ItmInfo array
...//some variables
}Head;
struct ItmInfo{
...    //some variables
}Itm;  //struct for Item
int main()
{
struct Header *head=malloc(1*sizeof (*head)); //open a header array, currently it have only 1 member 
struct ItmInfo *itm= malloc (memStack*sizeof(*itm));// open a item array

head[0].itmAddress = itm; //copy item array address in to the header
printf ("Address of item list is %pn",*itm);
printf ("Address in header is %pn",head[0].itmAddress);
return 0;
}

这段代码可以运行,但是,这些地址不在同一个值

结果:

Address of item list is 000000000061fd20
Address in header is    0000000000081490
我做错了什么,首先这样做是可以的吗?,谢谢你
printf ("Address of item list is %pn",*itm);

应该

printf ("Address of item list is %pn", (void *)itm);

将指针解引用并将整个结构推入堆栈(它可以是兆字节的数据,如本例中的80.000.000字节的数据:)https://godbolt.org/z/qYMM67)。

要显示存储在itm指针中的引用。

printf ("Address of item list is %pn", (void *)itm);
printf ("Address in header is %pn", (void *)head[0].itmAddress);

https://godbolt.org/z/8sdvhT

如果转换为void *,则printf ("Address of item list is %pn",(void *)*itm);行永远不会编译

最新更新