Dynamic size of struct

O

ose

If a struct declared as:

struct x {int a; int b; string c;}

Since string c's content could be changed at runtime, does this mean that
"sizeof struct x" could be dynamic and changed at runtime as well? Is this a
good, valid way of using "struct"?
 
K

Kai-Uwe Bux

ose said:
If a struct declared as:

struct x {int a; int b; string c;}

Since string c's content could be changed at runtime, does this mean that
"sizeof struct x" could be dynamic and changed at runtime as well?
No.

Is this a good, valid way of using "struct"?

Your member names are a little bit on the meaningless side. But the struct
is clearly valid and sometimes a struct like that (with better named
fields) even qualifies as good style.


Best

Kai-Uwe Bux
 
W

William Woody

"ose said:
If a struct declared as:

struct x {int a; int b; string c;}

Since string c's content could be changed at runtime, does this mean that
"sizeof struct x" could be dynamic and changed at runtime as well? Is this a
good, valid way of using "struct"?

By 'string' I presume you mean the C++ standard string class.

Internally the std::string class maintains a pointer to a string; thus,
'string c' in your declaration above is akin to:

struct x { int a; int b; struct { overhead decls; char *ptr; } c };

Because you don't know the size of std::string because the overhead it
maintains is not defined, you cannot predict the size of struct x;
however, the overall size of struct x is fixed.

Internally variable length strings are maintained by the std::string
class by the equivalent of realloc() on ptr; thus, your struct points to
another chunk of memory that may bounce around and change size in the
heap as you manipulate the string c.

Hope this helps.

--
William Edward Woody - (e-mail address removed)
Chaos In Motion - http://www.chaosinmotion.com

Freedom is the non-negotiable demand of human dignity;
the birthright of every person‹-in every civilization.
- National Security Strategy of the United States
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top