Thread: How to interpret char* into a struct?

  1. #1
    Registered User
    Join Date
    Sep 2020
    Posts
    2

    How to interpret char* into a struct?

    If I have a char* which I know contains data already and want to interpret this data as a struct, how can I safely do this?

    E.g if I have

    Code:
    struct s
    {
        int i;
        float f;
        short s;
    };
    
    char* c;
    ...
    // c points to valid data now
    I know you can't do

    Code:
    struct s* data = (struct s*)c;
    as this violates strict aliasing rules so I was wondering if the safest way would be to use memcpy assuming the struct is packed?

    Code:
    struct s data;
    memcpy(&data, c, sizeof(struct s));
    Also is casting to
    Code:
    void*
    first then the struct allowed?

    Code:
    struct s* data = (struct s*)(void*)c;
    Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,629
    The memcpy is the only way to go.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2020
    Posts
    2
    Quote Originally Posted by Salem View Post
    The memcpy is the only way to go.
    Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 03-22-2016, 10:45 AM
  2. Replies: 26
    Last Post: 02-18-2012, 02:59 AM
  3. How would you interpret this...
    By Strahd in forum C Programming
    Replies: 4
    Last Post: 09-23-2011, 10:29 PM
  4. C++ Casting (re-interpret cast)
    By Davros in forum C++ Programming
    Replies: 21
    Last Post: 07-20-2004, 03:53 PM
  5. How does hardware interpret data?
    By Silvercord in forum Tech Board
    Replies: 3
    Last Post: 01-29-2003, 01:46 PM

Tags for this Thread