BigO
BigO

Reputation: 98

Equality of structure using pragma pack in C

The reason behind the fact that the structures can't be checked for equality in C is the presence of slack bytes,which makes the comparison impossible.

But if I use #pragma pack(1) which removes the slack bytes then the comparison should be done smoothly,but it still gives error on being compared.

Example Code

#include<stdio.h>
#pragma pack(1)
struct person
{
    int uid;
    char nameStart;
};
struct personDupe
{
    int uid;
    char nameStart;
};
int main()
{
    struct person var;
    struct personDupe varDupe;
    printf("\nSize of person : %3d\n",sizeof(var));
    printf("\nSize of personDupe : %3d\n",sizeof(varDupe));

    var.uid = 12;
    var.nameStart = 'a';

    varDupe.uid = 12;
    varDupe.nameStart = 'a';

    if(var == varDupe)    //Error is introduced
        printf("\nStructures are equal\n");
    return 0;
}

Upvotes: 1

Views: 338

Answers (2)

Bo Persson
Bo Persson

Reputation: 92211

You can also tell the compiler how you detect that two values are the same

bool same_person(struct person* p, struct personDupe* dupe)
{ return p->uid == dupe->uid && p->nameStart == dupe->nameStart; }

And then you can do

if(same_person(&var, &varDupe))
    printf("\nStructures are equal\n");

Upvotes: 1

Jack
Jack

Reputation: 133557

Your code doesn't compile since you can't compare directly two struct.

You should use something like memcmp:

memcmp(&var, &varDupe, sizeof(var));

This doesn't solve the padding problem, which can be solved by ensuring that a struct is properly initialized to a known value even on padding bytes (which can be obtained by memset prior to initialization of fields).

But the approach of packing a struct to remove padding just to check if they are equal seems a fragile solution. If the compiler wants padding then it has a good reason for it, possibly performance related.

Upvotes: 2

Related Questions