Write a program to compare two objects of a structure.
Ans
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int
main ( void )
{
struct A {
int _1; /* sizeof ( int ) == 4 */
int _2;
float _3; /* sizeof ( float ) == 4 */
char _4; /* sizeof ( char ) is always == 1 */
}a, b;
/* initialize a and b */
...
if ( memcmp ( &a, &b, sizeof a ) == 0 )
puts ( "The two structures are equal" );
else
puts ( "The structures are unequal" );
return EXIT_SUCCESS;
}
This program is very general, and might invoke undefined
behaviour. To make a structure object properly aligned,
the compiler inserts padding bytes whenever (or wherever)
necessary. The Standard does not specify what value these
padded bytes should take. In this example, the objects,
a and b, looks like this:
4 bytes 4 bytes 4 bytes 4 bytes (enlarged)
______ ______ ______ ____ ____ ____ ____
| _1 | | _2 | | _3 | | _4 | P | P | P |
------ ------ ------ ---- ---- ---- ----
Byte # 0 4 8 12 13 14 15
P is a padding byte in the above illustration, whose value
is undefined. Some compilers may initialize such bytes to
zero, or some may leave it untouched. And, memcmp() compares
padding bytes also, even though these bytes have no meaning!
A more portable and dependable solution is to compare structure
members-by-member, i.e.,
if ( a._1 == b._1 &&
a._2 == b._2 &&
a._3 == b._3 &&
a._4 == b._4 )
puts ( "The two structures are equal" );
else
puts ( "The structures are unequal" );