Alex Rivera | Logout

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

Asked 2011-06-26T18:40:38.053
14

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);
}
c
Edit
Report

2 Answers

6

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 structs, you should explicitly compare their elements.

answered 2011-06-26T18:47:08.057
-1

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*/
 }
answered 2011-06-27T03:59:07.867

Your Answer