In main class I print sizeof(person->name) and then I do sizeof(name) which are same as I pass same char array to Person constructor. But why I get varied results in both cases
in first case sizeof returns 32 whereas in second case sizeof return 6 This is output
This is the code :-
#include <iostream>
#include "Person.h"
int main()
{
char name[] = {'H','o','b','b','i','t'};
Person *person = new Person(name , 203);
std::cout << "p->Name size - " << sizeof(person->name) << " char array size " << sizeof(name) << std::endl;
delete person;
return 0;
}
#include "Person.h"
#include <iostream>
Person::Person(){};
Person::Person(char name[],int age)
{
this->name = name;
this->age = age;
}
Person::~Person()
{
std::cout << "\n Destructor called" << std::endl;
}
void Person::sayHello()
{
std::cout << "\n Hello " << this->name << " " << this->age << std::endl ;
}
sizeof
in a std::string
does not measure the complete amount of memory the string occupies. It measures how large the std::string
object is.
The sizeof
on a std::string
is a constant value that is independent on the length of the string that is stored in it.
A std::string
does have an overhead compared to a char name[]
due to meta information and small string optimizations, and that overhead is (depending on the implementation) at a maximum of around 20 bytes.
For a range of 0 - ~20 chars a std::string
will always occupy ~20 bytes memory. For more than ~20 chars the std::string
will occupy ~20 + number of char bytes.
So yes for a really small number of chars it can be 5 times more bytes. But for a normal use case, that overhead can be ignored.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.