I have some doubt related to the following code:


In the above code,
1)a.length(); given output as 4 so this means all strings never include ‘\0’ character??
2) Should’nt sizeof(a)/sizeof(a[0]); also give same output but it gives 32 as output. Why??

Hello @sahilkhan2312000131 there is difference between size of and length.
and the difference is Sizeof gives actual size of any type of data (allocated) in bytes (including the null values) whereas length will give you the length of a string.

I know about that. Can you please explain this:
1)a.length(); given output as 4 so this means all strings never include ‘\0’ character??
2) Should’nt sizeof(a)/sizeof(a[0]); also give same output but it gives 32 as output. Why??

@sahilkhan2312000131 null character is not included in the length it just represents the ending of the string.

This is not giving the same output as I told you the difference between the length and the size of

But sizeof(a)/sizeof(a[0]) becomes length only no?? It works fine in case of int array

it is same for both strings and character arrays?

No its not same:

Not able to get what you are saying

@sahilkhan2312000131
When you take sizeof on a pointer type, you’ll get the size in bytes of the memory address. In this case 8 is the size of the address (in bytes).

see it depends on your machine as well:
check this code even when i am giving string much longer then also the ouput is same.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

@tarunluthra
@rhlbhrdwj3

pls check …

Not really.
The string here in question is not a character array or a pointer. We are talking about an object of the string class that is defined in <cstring> library ( or <string.h> … both works).
This string class would have some definition written with several functions and other data variables. The exact implementation of this class would vary from compiler to compiler and from different C++ version to version. However most of it should be same to maintain uniformity. If the implementation is too different, it would create problems as well.

string a;
cout << sizeof(a);

In the above snippet, when you try to find the size of the object ‘a’, it actually returns you the size of string class object itself. This size is calculated by the compiler based on its internal implementation taking in account all the data variables and functions inside it.

In your doubt, you seem to be confusing this string class object with a character array. The two are entirely different and should not be mixed.

2 Likes