Variable | Sololearn: Learn to code for FREE!

0

Variable

Hello, While coding you have noticed that if you select float or int data type for string data.. Error says, Can't convert to float from 'const char*' And this two words also help you to create a string type variable.. Now the question is, Does, c++ counts strings as an constant array of characters?? https://code.sololearn.com/crbf4UI58Wd3/?ref=app Another thing const char* - - - 8bits string - - - 32bits Why??

4/13/2021 12:51:27 AM

Mohammad Mehedi Hasan

4 Answers

New Answer

+3

The sizeof compiler operator returns the size in bytes not bits. The const char * is 8 bytes (64-bits) because it is a pointer on a 64-bit system The string is 32 bytes in size because it is an object and contains more than just the characters in the string. if you wish to convert a numeric type to a string use the std::to_string() function int i = 42; double d = 123.456; string stri = to_string(i); string strd = to_string(d); See: https://www.cplusplus.com/reference/string/to_string/

+1

C++ string can not be seen as a character array because the quality of changeable length of characters. As we all know array is fixed sized. std::string works like array because you access the character like you do in array, but in reality it's not an array. About sizeof, An array is a type that allocate a continuous memory to store the elements of the same data type, while std::string is a class and rather complicated. We do not really know how std::string is implemented, but since it's a class, we can guess that it has other various members and functionality which potentially increase the size of a string.

0

0

CarrieForle, the underlying data structure in a string is a char array. Even plain old C can have dynamic arrays, that's what realloc is for, so the array is not of a fixed size. To access the underlying char array in a string use the std::string::c_str() method. http://www.cplusplus.com/reference/string/string/c_str/ or the std::string::data() method. http://www.cplusplus.com/reference/string/string/data/