问题
I have a struct
:
struct st
{
short a;
int *b;
char ch;
};
short
is 2 bytesint*
is 8 bytes in x64char
is 1 bytes
All the above together should give me 11 bytes. But if I do sizeof(st)
I get 24 bytes. Why the struct
uses more memory and how to reduce the memory to 11 bytes?
回答1:
pragma pack
is usually what is used, but its not as portable as you'd like. Here's the docs on it:
- Microsoft's pack
- GCC's Structure-Packing Pragmas
Both provide #pragma pack(n)
, push
, and pop
.
In the absence of the packing, try reordering the struct
:
struct st
{
int *b;
short a;
char ch;
};
You have to be careful about accessing data if its packed. You will probably have to memmov
(or memcpy
) it out to ensure portability across all platforms. If you don't, then you could encounter a EXCEPTION_DATATYPE_MISALIGNMENT
on Windows or a SIGBUS
error on Linux.
Microsoft has a good writeup on it at Windows Data Alignment on IPF, x86, and x64.
-Wstrict-aliasing
and -Wcast-align
will help you find the sore spots.
回答2:
I know this is late and I know you already accepted an answer but this can also work.. You'll get 12 bytes.. NOT 11. I'm not sure if it's portable but I think it is. See here: http://en.cppreference.com/w/cpp/language/alignas
#include <iostream>
struct alignas(char) aligned_struct
{
short a;
int *b;
char ch;
};
int main()
{
std::cout<<sizeof(aligned_struct);
}
EDIT:
VS2012 does NOT include alignas in their compiler according to: http://msdn.microsoft.com/en-us/library/vstudio/hh567368(v=vs.110).aspx
It doesn't seem to need the above in VS2012 though. For some reason, with or without the above, it still prints 12:
struct aligned_struct
{
short a;
int* b;
char ch;
};
int _tmain(int argc, _TCHAR* argv[])
{
std::cout<<sizeof(aligned_struct); //prints 12
std::cin.get();
return 0;
}
来源:https://stackoverflow.com/questions/21010346/minimize-total-struct-memory