sizeof () string is reported as 28 ???? Why????

D

dwaach

Hi,

In the following program,

#include <iostream>
using namespace std;

class A
{
public:
string name;
char address[256];
};


int main()
{
A oa;
cout<<sizeof(oa.name)<<endl;
cout<<sizeof(oa.address)<<endl;
return 0;
}

Output is,
28
256

Why is string size as 28.

???

Thanks
Abhi
 
I

Ian Collins

dwaach said:
Hi,

In the following program,

#include <iostream>
using namespace std;

class A
{
public:
string name;
char address[256];
};


int main()
{
A oa;
cout<<sizeof(oa.name)<<endl;
cout<<sizeof(oa.address)<<endl;
return 0;
}

Output is,
28
256

Why is string size as 28.
What did you expect?

You are outputting the size of a std::string object, not the contents of
name.
 
R

Roland Pibinger

int main()
{
A oa;
cout<<sizeof(oa.name)<<endl;

cout << oa.name.length() << endl; // or oa.name.size()
cout<<sizeof(oa.address)<<endl;
return 0;
}

sizeof(oa.name) is the size of the string object. Your library uses
some implementation optimizations which make the object that large.
 
N

nevergone

#include <iostream>
using namespace std;

class A
{
public:
string name;
char address[256];

};

int main()
{
A oa;
cout<<sizeof(oa.name)<<endl;
cout<<sizeof(oa.address)<<endl;
return 0;

}

Output is,
28
256

Why is string size as 28.

???

Thanks
Abhi

in g++, ubuntu
the output is:
4
256
 
R

Roland Pibinger

in g++, ubuntu
the output is:
4
256

Impelentation and performance characteristics of string are not
standardized. g++ probably uses a ref-counted string implementation
with 'copy-on-write' whereas Microsoft/Dinkumware uses SSO (small
string optimization) with an internal buffer resulting in cheap
creation and copying for 'short' strings but expensive copying for
'long' strings.
 
O

outmatch

dwaach 写é“:
Hi,

In the following program,

#include <iostream>
using namespace std;

class A
{
public:
string name;
char address[256];
};


int main()
{
A oa;
cout<<sizeof(oa.name)<<endl;
cout<<sizeof(oa.address)<<endl;
return 0;
}

Output is,
28
256

Why is string size as 28.

???

Thanks
Abhi
sizeof(std::string) depends on different implemention. It could be only
a pointer, or a struct.
 

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

Forum statistics

Threads
473,995
Messages
2,570,231
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top