size of struct

Started by
3 comments, last by Bregma 13 years ago
I want to know how a struct object varies in size with a string or char[] member variable.

It seems the object is always 32 byte long nomatter what the string is. Is the string actaully in heap and the variable name is really just a pointer to a dynamic string array?

I am asking because I want to send structs over WinSock and I need to cast a Char Buffer[] into a struct.


#include <iostream>
#include <string>

using namespace std;

struct Obj{
string name;
};

void main(){

Obj test1, test2;
test1.name = "123";
test2.name = "1234";

cout << "test1: " << sizeof(test1) << " " << test1.name << endl;
cout << "test2: " << sizeof(test2) << " " << test2.name << endl;

test1.name = "12345678901234567890123456789012345678901234567890";
test2.name = "test1234aedgegy";

cout << "test1: " << sizeof(test1) << " " << test1.name << endl;
cout << "test2: " << sizeof(test2) << " " << test2.name << endl;

system("pause");
}
Advertisement
It's always 32 bytes because your structure has a std::string, which is 32 bytes. So you're basically doing sizeof(std::string)

You may want to try:
test1.name.size()
test2.name.size()

Which will give you the length of the string.
The structure, as you suspect, contains only a reference to a string object, not the string itself.

NOTE:
Don't use sizeof( variable-name)! Use sizeof( data-type ). sizeof() is not a function, it's a compile-time operator and doesn't calculate anything at run-time.

You'll have to use name.length() or something similar.

EDIT: ninja'd

Please don't PM me with questions. Post them in the forums for everyone's benefit, and I can embarrass myself publicly.

You don't forget how to play when you grow old; you grow old when you forget how to play.

The compiler will pad structs and classes to speed up reading/writing to it, if you want to want your struct to spend as little space as possible then you need to pack it
http://msdn.microsoft.com/en-us/library/2e70t5y1%28v=vs.80%29.aspx

It seems the object is always 32 byte long nomatter what the string is. Is the string actaully in heap and the variable name is really just a pointer to a dynamic string array?

Yes, a std::string has a fixed size. It may or may not keep the actual string in dynamic storage duration, depending on if your implementation uses the SSO (short string optimization) or not.

You will find marshalling an internal data structure over a network will meet with doubleplus ungood fail if all you do is dump binary. You need to use a wire protocol and stick with it. Issues such as endianness, padding, ABI compatibility, word sizes, opaque structure, and pointers will bite you sharply in the bump the moment you deviate from the machine you tested on.

Stephen M. Webb
Professional Free Software Developer

This topic is closed to new replies.

Advertisement