Thread: Structs, members, and casting

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    9

    Question Structs, members, and casting

    I'm using a library that defines:
    Code:
    struct ip_addr {
      u32_t addr;
    };
    and which has functions that use pointers to these structures - e.g.
    Code:
    a_func(struct ip_addr *dst_ip);
    My code uses u32_t's to deal with IP addresses and I need to pass them to the library routines. Can I do this with some sort of clever casting, or will I have to create a new structure, set the addr member, and pass a pointer to it?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    You can get away with casting, something like:
    Code:
    u32_t ipAddr = 0xC0a80001;
    
    a_func((struct ip_addr *)&ipAddr);
    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Jun 2003
    Posts
    9
    Thanks, Mats

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Of course, that's relying on what the structure contains. If that ever changes in the future, you could end up in trouble.

    Some alternatives: in C99 and with GNU C, you can use anonymous, named member (for lack of a better name) initialized structures.
    Code:
    a_func(&(struct ip_addr){.addr = ipAddr});
    That's not standard C89, however.

    You could always use a function if you do this in several places -- if you don't care about thread-safeness:
    Code:
    struct ip_addr *u32_to_ip_addr(u32_t num) {
        static struct ip_addr ip;
        ip.addr = num;
        return &ip;
    }
    That's what I'd probably do.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    Registered User
    Join Date
    Jun 2003
    Posts
    9
    Good point. Thanks, DWK.

Popular pages Recent additions subscribe to a feed