3

When I run this code, result is always 24 regardless of what string is. Why?

#include <bits/stdc++.h>
using namespace std;
    
int main()
{
    string s = "asdccccc";
    cout << sizeof(s);
    return 0;
}
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • To get the size of a string use `cout << s.size();` (or `cout << s.length();` ... they're synonymous). When you do `sizeof(s)`, you are not getting the size of the string's payload, you are getting the size of the string object that owns the payload. – Eljay Sep 07 '21 at 14:55
  • @Caleth I should have known this was a duplicate, thanks. – Mark Ransom Sep 07 '21 at 16:38
  • Your compilation will be more efficient if you use `#include `, this is a single include file version the unstandard behemoth `bits/stdc++.h`. In general, only include the headers that actually resolve symbols in your code or header. – Thomas Matthews Sep 07 '21 at 17:27

2 Answers2

4

A string is an object. By using sizeof you are getting the size of the members of that object. One of those members is probably a pointer to the actual string contents, but the size of a pointer is constant no matter what it points to.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • i tried running it on other compilers...answer wasn't 24 but it was still a constant number regardless of the size of the string... so the size of the pointer changes with compiler?? – Chirag Joshi Sep 07 '21 at 14:47
  • @ChiragJoshi The definition of the `std::string` class changes with the standard library implementation. The size of pointer doesn't change between compilers, but it does change between different CPU architecture (and x86 supports multiple modes that have differently sized pointers). – eerorika Sep 07 '21 at 14:49
  • @ChiragJoshi it could be the size of a pointer, especially if one is 32-bit and another is 64-bit. It could also be the number and type of other members. – Mark Ransom Sep 07 '21 at 14:49
2

Consider this simple example

class string
{
    const char* _ptr;
    ....
    ....
public:
   
}

When you write sizeof(string), you will get the size of the class, not the size of string literal _ptr points to.

Karen Baghdasaryan
  • 2,407
  • 6
  • 24