I am trying to compile the following code:
#include <iostream>
using namespace std;
void show1(string text1[]) {
cout << "Size of array text1 in show1: " << sizeof(text1) << endl;
}
int main() {
string text1[] = {"apple","melon","pineapple"};
cout << "Size of array text1: " << sizeof(text1) << endl;
cout << "Size of string in the compiler: " << sizeof(string) << endl;
show1(text1);
return 0;
}
And the output is shown below:
Size of array text1: 96
Size of string in the compiler: 32
Size of array text1 in show1: 8
I am not able to understand, why is the sizeof operator working on the same array giving two different outputs at two different points? Please explain.
text1for yourshow1function is really declared asstring* text1. And getting thesizeofof a pointer is the size of the pointer itself, not what it might point to. Usestd::vectororstd::arrayinstead.sizeof(string)is the size of thestd::stringstructure, not the size of the text in the string. See alsostd::string::length().