SP3coder
SP3coder

Reputation: 1

Sizeof operator on string array is giving different output in C++

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.

Upvotes: 0

Views: 269

Answers (2)

GobeRadJem32
GobeRadJem32

Reputation: 102

Try with member function 'size'.

Write this code:

#include <iostream>
using namespace std;
void show1(string text1[]) 
{
    cout << "Size of array text1 in show1: " << text1->size() << endl;
}

int main() 
{
    string text1[] = {"apple","melon","pineapple"};
    cout << "Size of array text1: " << text1->size() << endl;
    cout << "Size of string in the compiler: " << sizeof(string) << endl;
    show1(text1);
    return 0;
}

Description:

std::vector has a member function size(). And std::string too. In std::vector return size of vector(all elements). In std::string returns all elements in array.

Upvotes: 0

TonySalimi
TonySalimi

Reputation: 8427

The sizeof() operator returns the compile time size of the objects. It means that if your type allocates a memory chunk at run time from heap, that memory is not taken into account by sizeof().

For your first case, i.e.

 string text1[] = {"apple","melon","pineapple"};

You have an array of 3 strings, so sizeof should return 3*sizeof(std::string). (3*32 = 96 in your case)

For your second case:

sizeof(string)

It should simply print the size of an string. (32 in your case).

Finally for your last case, do not forget that arrays are passed using a pointer in C/C++. So, your parameter is simply a pointer and sizeof() should print the size of a pointer on your machine.

Edit: As @ThomasMatthews has mentioned in the comments, if you are interested in getting the real size of an string (i.e. the number of characters inside it), you can use std::string::length() or std::string::size().

Upvotes: 3

Related Questions