使用(。)运算符输出结构成员的值会得到与 - >不同的结果。运营商,为什么?

时间:2014-01-03 23:16:44

标签: c

当我尝试使用(。)运算符输出结构成员的值时会出现奇怪的结果,而不是 - >运算符,这是代码

typedef struct MonitoredDns
{
int16               dnLength;
char                setDn[26];
tDeviceId           setId;
tDeviceId           acquiredSetId;
tCallId             activeCallId;
tCallId             selectedCallId;
} MonitoredDns;

MonitoredDns* pMonitoredDn = (MonitoredDns*) malloc(sizeof(MonitoredDns));
MonitoredDns dnStruct = *pMonitoredDn;
mbMonitorDeviceBegin(dn, &dnStruct.setId);

//Now print setId value set by the mbMonitorDeviceBegin function using the two following methods
//%hu is for unsigned short as I think, setId is a tDevice which is uInt16
printf("before(1) AddDnToMonitoredDns SetID = %hu\n", pMonitoredDn->setId);
printf("before(2) AddDnToMonitoredDns SetID = %hu\n", dnStruct.setId);

2 个答案:

答案 0 :(得分:3)

MonitoredDns dnStruct = *pMonitoredDn;

执行此行后,dnStruct*pMonitoredDn不同,它是*pMonitoredDn副本。然后,您调用修改副本的方法,原始malloc版本仍未更改。

请尝试此操作,此版本将显示.->具有相同的结果。但是,这个版本与你的版本不同,因为pMonitoredDn指向的内存的生命周期现在只有方法持续时间,而malloc - 内存将持续直到free - 编辑

MonitoredDns dnStruct;
MonitoredDns* pMonitoredDn = &dnStruct;
mbMonitorDeviceBegin(dn, &dnStruct.setId);

//Now print setId value set by the mbMonitorDeviceBegin function using the two following methods
//%hu is for unsigned short as I think, setId is a tDevice which is uInt16
printf("before(1) AddDnToMonitoredDns SetID = %hu\n", pMonitoredDn->setId);
printf("before(2) AddDnToMonitoredDns SetID = %hu\n", dnStruct.setId);

答案 1 :(得分:0)

首先复制一下空结构。

然后你调用一个修改副本的函数。

然后你想知道为什么副本和原版不一样。