-2

I have an array of strings and I want to know the length of each of its constituent strings. All the strings are of different lengths but the compiler shows all of them to be of equal size. Anyone can explain why is it happening? Here's the code:

string arr[] = {"ACACACZCZCZC", "LOQWABCB", "PTUTCFEBC"};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"number of strings is "<<n<<endl;
cout<<"individual size of strings: str1 = "<<sizeof(arr[0])<<", str2 = "<<sizeof(arr[1])<<", str3 = "<<sizeof(arr[2])<<endl;

and this results in size of all strings as 8.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
Ankit Gupta
  • 99
  • 2
  • 5
  • 1
    Are you sure you don't want `arr[0].length()` or `arr[0].size()` if you're actually after the number of characters in each string? – Cory Kramer Aug 17 '16 at 11:16
  • You could also use [strlen()](http://www.cplusplus.com/reference/cstring/strlen/) – DIEGO CARRASCAL Aug 17 '16 at 11:19
  • @CoryKramer I tried it and now it shows their variable lengths. Thanks. But why do all strings are taking equal space here(8 Bytes). Shouldn't the larger string be taking more space? Any ideas here?? – Ankit Gupta Aug 17 '16 at 11:22
  • Please read the [duplicate link](https://stackoverflow.com/questions/34560502/why-is-sizeofstdstring-only-eight-bytes) posted above. The size of a `std::string` does not directly include the size of the underlying character array, rather simply the pointer to that array. – Cory Kramer Aug 17 '16 at 11:23

3 Answers3

2

sizeof(x) gives you the size of object x. That has nothing to do with the size of resources potentially managed by the object. All this tells you that a std::string object consists of 8 bytes; most probably two pointers.

If you want to learn the length of the string, use the string's member function size:

arr[0].size()
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • @AnkitGupta: Don't forget to accept this answer if you've found it to be the most useful (which, IMHO, it is). – Bathsheba Aug 17 '16 at 11:25
1

sizeof(arr[0]) gives you the size in bytes of the std::string object, based on its static type.

If you want to know the length of the string the object holds, use std::string::size(), like this arr[0].size();

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • but even if increase the length of any string to, say 40, it still is showing its size as 8. shouldn't it increase if the length is increased as it is now taking more space? – Ankit Gupta Aug 17 '16 at 11:20
  • Nope. The `std::string` structure probably has a *pointer* to the data buffer, and the size of a pointer is not dependent on the buffer that it points to. – Bathsheba Aug 17 '16 at 11:21
0

sizeof T is a compile-time evaluable operator that returns the size in bytes of the type T.

It does not return the length of the string contained in std::string. If you want that then use size() or length().

Bathsheba
  • 231,907
  • 34
  • 361
  • 483