-4

I have this function:

void strPointerTest(const string* const pStr)
{
    cout << pStr;
}

If I call it like this:

string animals[] = {"cat", "dog"};
strPointerTest(animals);

it returns the address of the first element. So I was expecting if I dereference it, I'd get the 1st element of the array but doing so like this:

void strPointerTest(const string* const pStr)
{
    cout << *(pStr);
}

It won't even let me compile. I tried this using int instead of string and it works. Is there something special with strings? How would I retrieve the elements of the string array in this function?

EDIT:

Here's a complete example and it won't compile on my end:

#include <iostream>

void strPointerTest(const std::string* const pStr);
void intPointerTest(const int* const pInt);

int main()
{
    std::string animals[] = { "cat", "dog" };
    strPointerTest(animals);

    int numbers[] = { 9, 4 };
    intPointerTest(numbers);
}

void strPointerTest(const std::string* const pStr)
{
    std::cout << *(pStr);
}

void intPointerTest(const int* const pInt)
{
    std::cout << *(pInt);
}

I don't know why the downvote. I'm asking for help because it won't compile on my end. If it works on your end doesn't mean it also works on mine. I'm asking for help because I don't know what's happening.

The compilation error is:

No operator "<<" matches these operands - operand types are: std::ostream << const std::string
g_b
  • 11,728
  • 9
  • 43
  • 80

1 Answers1

5

On some compilers <iostream>happens to also include the <string> header. On other compilers, specifically the Microsoft compiler, it apparently does not. And the I/O operators for strings are declared in the <string> header.

It is your responsibility to include all the needed headers, even if the code sometimes happen to work anyway.

So the fix is to just add

#include <string>

at the top of the file.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203