Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ string length in bytes

Tags:

c++

string

string str; str="hello"; str.length(); sizeof(str);

I see that str.length returns the length in bytes why sizeof(str) doesn't return the same?

Is there alternative in c++ to a c command which is strlen(str)? What is the alternative of this coomand in c++?

When I use winsock in the send function I return the length in bytes. What should I use? str.length? Or sizeof(str)? Pr something else? Because I see they produce different results.

like image 755
user2933572 Avatar asked Mar 04 '26 11:03

user2933572


2 Answers

sizeof returns the size of the data structure, not the size of the data in contains.

length() returns the length of the string that str contains, and is the function you want

It might seem confusing because sizeof(char[30]) is 30, but that is because the size of the data structure is 30, and will remain 30 no matter what you put in it

The string is actually an extremely complicated structure, but suppose it was a simple class with a pointer and a length

class string
{
    char *data;
    int length;
};

then sizeof(string) would return:

The size of a char * pointer, possibly but not necessarily 4

plus the size of an int, possibly but not necessarily 4

So you might get a value of 8. What the value of data or length is has no effect on the size of the structure.

like image 77
David Sykes Avatar answered Mar 06 '26 02:03

David Sykes


sizeof() is not really meant to be used on a string class. The string class doesn't store ONLY the string data; there would be no difference between its data and a C-style string; it has other stuff in it as well, which throws off sizeof(). To get the actual length of the characters in the string, use str.length().
Don't use the C strlen() on a C++ string object. Don't use sizeof() either. Use .length().

like image 27
Zach Stark Avatar answered Mar 06 '26 02:03

Zach Stark