Re: Structure size
LR wrote:
Bruce. wrote:
"Jim Langston" <tazmaster@rocketmail.com> wrote in message
news:YeSni.867$q7.308@newsfe05.lga...
"Bruce." <noone@nowhere.com> wrote in message
news:tlPni.11878$rL1.1904@newssvr19.news.prodigy.net...
"John Harrison" <john_andronicus@hotmail.com> wrote in message
news:vePni.402$Oi4.48@newsfe4-gui.ntli.net...
Since you aren't worried about padding bytes the obvious answer is
typedef struct
{
int var1;
int var2;
int var3;
char var4[ 1024 - 3*sizeof(int) ];
} MYSTRUCT;
Thanks but my example was oversimplified to keep it brief. The
actual structures are much more complex, too complex for a
solution like that. I guess what I was looking for doesn't exist.
But thanks anyway.
Someone already showed you how to use it. Use a union.
#include <iostream>
typedef union
{
struct {
int v1;
int v2;
int v3;
} var;
char unused [1024];
} MyStruct;
int main(void)
{
MyStruct Foo;
std::cout << sizeof( Foo ) << "\n";
Foo.var.v1 = 10;
Foo.var.v2 = 20;
Foo.var.v3 = 30;
}
var.v1 will start at position 0.
You forgot var4. I need var4 to be sized automattically to achieve a
structure size of 1024. I need var4 to the size of the remaining
space up to 1024 bytes. In this case it would be:
struct {
int v1;
int v2;
int v3;
char v4[1024 - 12];
} var;
But I want the compiler to figure the 12 automattically.
I'm not sure that I follow what you mean here, but if I do, then I
think that your best bet might be to use either some very complicated
#defines, or perhaps a template. Maybe something like this:
(I'm assuming that as you said in another post, you don't have a
portability problem and you can control your compiler to take care of
packing issues.)
struct x1 {
int a,b,c;
};
struct x2 {
int a; double e,f,g,h,i;
};
template<typename T>
struct Message {
T t;
char v[1024 - sizeof(T)];
};
then, else where you can...
Message<x1> m1;
Message<x2> m2;
there will be the added annoyance of having to reference the
individual members of x1 and x2 by doing something like m1.t.a = 43;
It might be wise to pick a better name for t.
[..]
I am not sure here, but I believe there is no guarantee that the size
of the 'Message<x1>' or 'Message<x2>' is actually going to be 1024
even with the mechanism you give here. I wonder, however, if there
is something in the Standard related to the sizes (and alignments)
that I missed, and it might actually impose certain limitations thus
giving programmers more leeway when it comes to determining type sizes.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask