->size() returns the wrong result

I'm using the ->size() operator to compute the number of elements in an array of strings, but the result is clearly wrong (returns 1 for a 2-element array).
How can I fix my code?

1
2
3
4
5
6
7
8
9
10
11
#include <string>
#include <iostream>

using namespace std;

int main() {
    string StringArray[]={"A","B"};
size_t size_string_array=StringArray->size();
cout<<size_string_array;

}
Doesn't it do what you asked? The only thing that StringArray is going to point to is the first element, which is the string "A".

The size of "A" is 1. If you change it to "AAA" you will get 3.

If you want an answer 2 then use vector<string> StringArray = ... and then StringArray.size().
Oh, thanks. I actually thought StringArray->size() was the right way to get the number of elements.

By the way, you said
The only thing that StringArray is going to point to is the first element


Is this so because " Array name is a pointer to the first element of the array", as I found on a website (don't know if I can post the link)?

Is this so because " Array name is a pointer to the first element of the array", as I found on a website (don't know if I can post the link)?


While an array decays to a pointer quite easily this is not the reason your code is producing the output you're getting. The reason is because you're using the operator-> when accessing the array.

And remember a raw array has no member functions.

All of these syntaxes call the size() member function of first std::string element of the array StringArray:
1
2
3
4
StringArray->size();
(*StringArray).size();
(*(StringArray+0)).size();
StringArray[0].size();


std::array has syntactic sugar that the plain array does not:
1
2
3
std::array<std::string,2> StringArray = {"A", "B"};
size_t elements_in_array = StringArray.size();
size_t length_of_first_string = StringArray[0].size();
Topic archived. No new replies allowed.