[英]Why I am getting varied results when using sizeof for same char array?
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.在主类中,我打印 sizeof(person->name) 然后我做 sizeof(name) 这与我将相同的 char 数组传递给 Person 构造函数相同。 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在第一种情况下 sizeof 返回 32 而在第二种情况下 sizeof 返回 6这是输出
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. std::string
中的sizeof
不测量字符串占用的完整内存量。 It measures how large the std::string
object is.它测量
std::string
对象的大小。
The sizeof
on a std::string
is a constant value that is independent on the length of the string that is stored in it. std::string
上的sizeof
是一个常量值,与存储在其中的字符串的长度无关。
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.由于元信息和小字符串优化,
std::string
与char name[]
相比确实有开销,并且该开销(取决于实现)最多约为 20 个字节。
For a range of 0 - ~20 chars a std::string
will always occupy ~20 bytes memory.对于 0 - ~20 个字符的范围,
std::string
将始终占用 ~20 字节内存。 For more than ~20 chars the std::string
will occupy ~20 + number of char bytes.对于超过约 20 个字符,
std::string
将占用约 20 + 字符字节数。
So yes for a really small number of chars it can be 5 times more bytes.所以是的,对于非常少的字符,它可以是 5 倍多的字节。 But for a normal use case, that overhead can be ignored.
但是对于正常用例,可以忽略该开销。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.