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