Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why whole structure can not be compared in C, yet it can be copied?

Tags:

c

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);
}
like image 690
MCG Avatar asked Jun 26 '11 18:06

MCG


People also ask

Why we Cannot compare structures in C?

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.

Can structures be compared in C?

C provides no language facilities to do this - you have to do it yourself and compare each structure member by member.

Can struct be copied?

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.

Can we compare two structures using any built in operator?

Yeah. It is relational operator. Relational operators are only used to compare two or more things.


1 Answers

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.

like image 102
Hans Passant Avatar answered Sep 28 '22 09:09

Hans Passant