+ 1
Explain me this code please. Why in case of string sizeof () is giving wrong answer?
6 Réponses
+ 3
Thanks to Shadow I don't need to explain the string part. But its size will depend on the machine architecture/implementation, for example in my 32 bit machine the space allocated to the string was 12 Bytes.
Now the array part. As I think you know, all C/C++ char arrays has a hidden additional character, the termination character '\0', so when you made "char b[] = "hello"", the compiler set the size of array b to fit the word hello plus the \0 character, so this means 6 characters in total, that is exactly what you are getting as reply.
Any doubt remaining?
+ 2
std::size() is a function included in the header <iterator>, however, it is a quite new feature (C++ 17), so not all compilers might support it yet. Reference:
https://en.cppreference.com/w/cpp/iterator/size
Now for the question.
First of all, sizeof() does not give a wrong answer! String "a" is actually 32 byte. This is due to how modern strings are implemented in C++. They are not simple arrays, but actually closer to vectors. What's so special about vectors is that they can grow in size, unlike arrays. And exactly for these grow-operations, vectors always allocate a bit more memory space than they actually need. So string "a" allocated space for 32 characters, but only 5 are used at the moment. That's were the difference comes from.
I'd suggest you to search more about vectors to understand how they work, etc.
I'll provide a few links you can start with:
http://www.cplusplus.com/reference/vector/vector/
https://en.cppreference.com/w/cpp/container/vector
https://www.geeksforgeeks.org/vector-in-cpp-stl/
+ 1
I tried it first on VS 2015 and it worked correctly when i wrote size (a)...However now i understood that size () is function of string library and it should be used as a.size () but still my question is why does sizeof () is giving wrong answer?
+ 1
+ 1
Hi Iterator,
I change your code a bit, try this:
#include <iostream>
#include <string>
using namespace std;
int main() {
string a="hello";
char b[]="hello";
char *c;
char d[10];
char e;
cout<<sizeof(a)<<endl;
cout<<sizeof(b)<<endl;
cout<<sizeof(c)<<endl;
cout<<sizeof(d)<<endl;
cout<<sizeof(e)<<endl;
return 0;
}
0
Hi Iterator,
In my attempt to understand the behavior of your code I compiled it with other C++ compilers and both them give a compilation error due to the function size(), from which library this function comes from?
When experimenting with C++ code here in sololearn I recommend you to try true c++ compilers, either installed in your machine or online, you can find one in www.cpp.sh, I say this because the c++ compiler/interpreter in sololearn is simple shitty and buggy.
So, go ahead, fix your code to compile with a true compiler and I will try to explain why you are getting these differences. Spoiler: the reason is due to how a string is represented with an array of char and also the string c++ object contents.