Why whole structure can not be compared in C yet it can be copied? In other words, Why comparison in below program does not work? It does not print string.
#include <stdio.h>
#include <string.h>
int main(void)
{
struct emp
{
char n[20];
int age;
};
struct emp e1={"David",23};
struct emp e2=e1;
if(e2 == e1)
{
printf("The structures are equal");
}
return(0);
}
Because the operator == is not aware of all the members of the structure it would need to compare, you are! You can't compare strings either, in C - at least, not with '==' or equivalent.
C provides no language facilities to do this - you have to do it yourself and compare each structure member by member.
A struct variable in Golang can be copied to another variable easily using the assignment statement(=). Any changes made to the second struct will not be reflected back to the first struct.
Yeah. It is relational operator. Relational operators are only used to compare two or more things.
You could use memcmp(). That's not a good idea in general though, structures tend to have padding bytes between the fields. The padding is used to align the field. Your structure doesn't have any but that's by accident. That padding can have any kind of value, making memcmp() fail to work because it sees all the bytes, not just the ones in the fields.
There's more, you have a C string in the structure. It can contain any kind of bytes past the zero terminator. Using strcmp() on the strings would return 0 but memcmp() again fails because it sees all the bytes. Pointers would be yet another failure mode.
Compare one field at a time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With