c++ sizeof() not returning correct size [duplicate]

廉价感情. 提交于 2019-12-24 19:29:17

问题


I'm trying to get the size of a string in my program, so then I can convert it into a char later using a loop, but the size that the program is returning is 5 numbers lesser than the actual size. Why would this be happening?

std::string theFileName = fileNames[ curTab ];
int size = sizeof( theFileName );

When debugging my program, it stores this in theFileName:

theFileName = "C:\Users\Vincent\Desktop\Untitled.txt"

And this in size:

size = 32

If you count the characters in theFileName, its actually 37. What is causing this to happen? I'm using MS Visual C++ 2010 Express, creating a notepad program.


回答1:


sizeof tells you the size of the data structure and all its member data. However, a string object will typically store the string data on the heap -- i.e. it's not member data, but the object owns it and stores a pointer to it.

The correct way to get the size of your string object is to call the size() or length() member function.




回答2:


std::string is not an array of chars. Is a dynamic array managed by the std::string object. sizeof returns the size of the specified data type, in the case of string, the pointer to the array plus an amount of statically allocated chars (Thats a common string optimization).

What you should use is the builtin function size(), which returns the length of the string.




回答3:


The size of the content is determined with

theFileName.size()

while sizeof returns the size of the object std::string. The object could, for example, contain a pointer to the location of the content and an unsigned integer to represent the length. sizeof would therefore contain the size of one pointer and the unsigned integer. This would not vary if you change the content.




回答4:


The size of a std::string object is unrelated to the size of the string it contains. Use the std::string member function provided for this purpose.




回答5:


sizeof is used to calculate the size of any datatype measured in bytes.

The function you have to use in your program is size.



来源:https://stackoverflow.com/questions/19758505/c-sizeof-not-returning-correct-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!