struct allocation in memory

Is there a way to guarantee that a struct is allocated contiguosly in memory?

Here's my problem: I'm reading the header of a binary file into a relatively big structure (~6Kb).
The first 4 members of the structure are:

long signature;
float version;
short mode;
long length;

If I just look at the addresses of these members I see:
signature : 0x9c085c8
version : 0x9c085cc
mode : 0x9c085d0
len : 0x9c085d4

which are definitely not contiguous.
Is there a way to force the struct to be contiguous so I can read it all at once? Or do I have to read each member separately (that would be quite annoying as the struct has more than 300 members...)?

thanks
nico

[hr]
[italic]How beautiful, if Sorrow had not made sorrow more beautiful than Beauty itself.[/italic]
JOHN KEATS

Comments

  • : Is there a way to guarantee that a struct is allocated contiguosly
    : in memory?
    :
    : Here's my problem: I'm reading the header of a binary file into a
    : relatively big structure (~6Kb).
    : The first 4 members of the structure are:
    :
    : long signature;
    : float version;
    : short mode;
    : long length;
    :
    : If I just look at the addresses of these members I see:
    : signature : 0x9c085c8
    : version : 0x9c085cc
    : mode : 0x9c085d0
    : len : 0x9c085d4
    :
    : which are definitely not contiguous.
    : Is there a way to force the struct to be contiguous so I can read it
    : all at once? Or do I have to read each member separately (that would
    : be quite annoying as the struct has more than 300 members...)?
    :
    : thanks
    : nico
    :
    : [hr]
    : [italic]How beautiful, if Sorrow had not made sorrow more beautiful
    : than Beauty itself.[/italic]
    : JOHN KEATS
    :

    You have to pack the struct together to 1 byte bounderies.

    This is compilier dependent.

    Microsoft Visual C++ uses:
    [code]
    #pragma pack (push, 1)

    struct foo {

    };

    #pragma pack (pop, 1)
    [/code]

    GCC uses:
    [code]
    struct foo {

    }__attribute__((packed));
    [/code]
    [hr][size=1][leftbr].:EvolutionEngine[rightbr][leftbr].:MicroOS Operating System[rightbr][leftbr][link=http://www.mt2002.sitesled.com]Website[rightbr][/link][/size]
  • : GCC uses:
    : [code]:
    : struct foo {
    :
    : }__attribute__((packed));
    : [/code]:

    That's exactly what I needed. Works perfectly!

    Thanks
    nico

    [hr]
    [italic]How beautiful, if Sorrow had not made sorrow more beautiful than Beauty itself.[/italic]
    JOHN KEATS
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion