Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   Dynamic size of struct (http://www.velocityreviews.com/forums/t627825-dynamic-size-of-struct.html)

 ose 07-27-2008 11:10 PM

Dynamic size of struct

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"?

 Kai-Uwe Bux 07-27-2008 11:44 PM

Re: Dynamic size of struct

ose wrote:

> 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

 William Woody 07-31-2008 12:28 AM

Re: Dynamic size of struct

In article
<1g7jk.269337\$SV4.229394@bgtnsc04-news.ops.worldnet.att.net>,
"ose" <ose29@hotmail.com> wrote:

> 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 - woody@alumni.caltech.edu
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

 All times are GMT. The time now is 10:15 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.