sizeof in c++ showing string size one less

后端 未结 4 764
逝去的感伤
逝去的感伤 2020-11-30 15:44

In C++ I am trying to get size of a string say \"gibbs\";

When I am using sizeof function it is returning me size less then one of actual s

4条回答
  •  心在旅途
    2020-11-30 16:27

    sizeof(s) in your example is returning the size of std::string, there is no relation to the content of what its members point to.

    How to fix this issue. We can add +1 always to return of sizeof but will that be perfect solution?

    no that won't solve anything because the value is constant, and sizeof is not providing the value you expect it does.

    if you want to know the number of characters required for the character sequence of the string, you can use s.length() or s.size() -- add 1 to that value to know the size required for a terminated string.

    also note that the value of sizeof is not going to be consistent across libraries and platforms. std::string implementations can vary greatly. in particular, you may see differences in pointer sizes and you may see small string optimizations.

提交回复
热议问题