CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Aug 2000
    Location
    California, USA
    Posts
    26

    How to determine the return value of sizeof(struct ...)

    I have created a struct which is composed of a char and a short. But the return value of sizeof( this struct) is 4 while I expect it to be 3. If I add a short, the the return value is 6.

    Is there a way to accurately predict the result of sizeof(struct or class)? Thanks!

    signature

  2. #2
    Join Date
    Oct 2001
    Posts
    238

    Re: How to determine the return value of sizeof(struct ...)

    The reason for it is the compiler sets things in memory 4 bytes apart since it increases performance. I don't know what you should do unless you add size of's for each member and get a total.


  3. #3
    Join Date
    Aug 2000
    Location
    California, USA
    Posts
    26

    Re: How to determine the return value of sizeof(struct ...)

    Thanks. I want to copy data from a byte buffer to an instance of this struct. If the bytes copied is too large, it may flush the memory. If I used a constant size, the next time I change the struct I'll have to change all the places this copy is performed.

    signature

  4. #4
    Join Date
    Sep 1999
    Location
    NJ
    Posts
    1,299

    Re: How to determine the return value of sizeof(struct ...)

    The value of sizeof correct (and it's not really a "return value" since sizeof is an operator, not a function)

    Give the struct:struct ABC
    {
    char a;
    short b;
    };

    You may think the size should be 3, but it's really 4. The difference is important when you do something like:Strct ABC abc[4];

    Here, &abc[1] starts 4 bytes from &abc[0].

    Most compilers have a way to allow you to force them to not align data (so that, for example, struct ABC really would be 3 bytes). For MS VC++, it's #pragma pack(1). For other compiler, you'll have to check their documentation.


    Truth,
    James
    http://www.NJTheater.com
    http://www.NovelTheory.com
    I don't do it for the points (OK, maybe I do), but rating a post is a good way for me to know if I helped.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured