Why whole structure can not be compared in C, yet it can be copied?
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=e开发者_JS百科1;
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.
struct
elements are usually aligned to some boundary, and when you initialize a struct
(especially one on the stack), anything in the bytes skipped by alignment will be uninitialized. Moreover, the contents of n
past the end of the constant initializer are not initialized. struct
comparison is defined as s1 == s2
doing memcmp(&s1, &s2, sizeof s1)
, whereas struct
initialization may or may not copy the skipped bytes. If you want to reliably compare struct
s, you should explicitly compare their elements.
It does not print string.
But it does not even compile :
error: invalid operands to binary == (have ‘struct emp’ and ‘struct emp’)
Beyond other correct things that have been said, remember that "comparing" is in general not a trivial action: it is so just for "primitive" basic types. Complex types (structs in this case) would need overloading ==, but C has no such concept.
In order to compare two "object" (structs) you have to write your own function that knows how to compare them, e.g. int compare_emp(const struct emp *, const struct emp *);
or similar.
just an idea, would casting it to a type such as void * and then comparing work? I was thinking something like
struct emp e1 = { "David",23 };
struct emp e2 = e1;
if (*((void*)&e1) == *((void*)&e2))
{
/* pure evil? I think not :3*/
}
But if you pass your value to a string, will it work?
void Comparethisvalue(emp a, emp b)
{
if(a.n.tostring()+a.age.tostring() == b.n.tostring()+b.age.tostring())
return true;
}
in code you can call
if(Comparethisvalue(e1, e2))
{
//do something
}
Or you can implicit do it:
void Comparethisvalue(emp a, emp b)
{
if(a.n == b.n && a.age == b.age)
return true;
}
精彩评论