Yazan Jaber
Yazan Jaber

Reputation: 2068

Output the value of a struct member using the (.) operator gives different results than -> operator, why?

Something strange happens when I try to output the value of a struct member using the (.) operator gives different results than -> operator, here is the code

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);

Upvotes: 0

Views: 61

Answers (2)

David Yaw
David Yaw

Reputation: 27864

MonitoredDns dnStruct = *pMonitoredDn;

After executing this line, dnStruct is not the same thing as *pMonitoredDn, it's a copy of *pMonitoredDn. You then call your method that modifies the copy, and the original malloc-ed version is still unchanged.

Try this instead, this version will show that the . and -> have the same result. However, this version isn't the same as what you had, because the lifetime of the memory pointed to by pMonitoredDn is now only as long as the method lasts, whereas the malloc-ed memory would last until free-ed.

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);

Upvotes: 3

bmargulies
bmargulies

Reputation: 100040

First you make a copy of the empty structure.

Then you call a function that modifies the copy.

Then you wonder why the copy is not the same as the original.

Upvotes: 0

Related Questions