Thread: How do I compare structures??

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    63

    How do I compare structures??

    Ppl,
    I am comparing two structures but C says that k>k2 and k==k2 are illegal for struct..how should I do it??
    A

    [code]
    int cmp(KEY k, KEY k2)
    {
    int result;

    if(k > k2)
    {
    result = 1;
    }
    else if(k == k2)
    {
    result = 0;
    }
    else
    {
    result = -1;
    }

    return result;
    }
    [\code]

  2. #2
    Registered User Zeeshan's Avatar
    Join Date
    Oct 2001
    Location
    London, United Kingdom
    Posts
    226
    1. You can compare all the members of the structures separately.

    2. You can create a function that would compare all the members of the structure, and return TRUE or FALSE.

    3. You can use operator overloading, if you know C++.

  3. #3
    Registered User
    Join Date
    Sep 2001
    Location
    Fiji
    Posts
    212
    As zeeshan said compare each member of the structure.

    Code:
    /* Structure one greater than struct two */
    int gt(struct name* one, struct name* two);
    
    /* struct two equal to struct one */
    int eq(struct name* one, struct  name* two);
    
    /* etc..*/
    
    struct name {
        int a;
        char b;
    };
    
    int main() {
        struct name x,y;
        x.a = 12;
        y.a = 12;
        x.b = 'x';
        y.b = 'y';
        if ( eq(&x, &y) ) {
            printf("There Equal\n");
        } else {
            puts("Not Equal");
        }
        return 0;
    }
    int eq(struct name* one, struct  name* two) {
       return (*one.a == *two.a && *one.b == *two.b);
    }
    Hope this helps

    kwigibo

  4. #4
    Im back! shaik786's Avatar
    Join Date
    Jun 2002
    Location
    Bangalore, India
    Posts
    345
    If the two structures being compared are of the same type, use memcmp(), a single line comparison!

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > use memcmp(), a single line comparison
    Don't do this.

    Structures can be padded, and the contents of padding bytes are undefined. memcmp doesn't know this and will blindly compare all bytes.

    The only thing to do is compare each member

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. compare structures
    By lazyme in forum C++ Programming
    Replies: 15
    Last Post: 05-28-2009, 02:40 AM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. Structures within Structures
    By Misko82 in forum C Programming
    Replies: 2
    Last Post: 08-27-2007, 12:25 AM
  4. pointers to arrays of structures
    By terryrmcgowan in forum C Programming
    Replies: 1
    Last Post: 06-25-2003, 09:04 AM
  5. Methods for Sorting Structures by Element...
    By Sebastiani in forum C Programming
    Replies: 9
    Last Post: 09-14-2001, 12:59 PM