Locally disable padding
Asked Answered
D

2

24

I write a parser for some data structure, after hours of debugging I found out that the problem is Visual Studio doesn't interpret the structures as I tell it. It seems some "padding" is used

struct foo { 
unsigned char a; //0x00
unsigned char b; //0x01
unsigned int c; //0x02
unsigned int d; //0x06
unsigned int e; //0x0A
unsigned int f; //0x0E
//0x12
};

I expected "sizeof(foo)=4*4+2=18" but I get "sizeof(foo)=20". Is there any possibility to turn padding off just for this special struct? I tried

__declspec(align(1)) struct foo { ...

but it does not work. Thank you for your help.

Dinse answered 19/1, 2012 at 21:40 Comment(3)
I think this article on MSDN will help.Mcintire
Are you compiling with /Zp 1?Ankerite
@MartinBroadhurst That would globally disable padding, The solution of hans works.Dinse
C
50

Use the #pragma pack directive for that:

#pragma pack(push, 1)
struct foo { 
  // etc..
};
#pragma pack(pop)
Cosec answered 19/1, 2012 at 21:44 Comment(0)
F
4

Visual Studio 2010 has #pragma pack to do what you're looking for.

Familist answered 19/1, 2012 at 21:43 Comment(3)
But wouldn't that affect all structs? I just want it locally for that one struct.Dinse
You can revert it afterwards - did you even read that documentation?Familist
You can use #pragma pack push/pop to get around that. Just push before and pop after the struct.Vibrator

© 2022 - 2024 — McMap. All rights reserved.