vehomzzz
vehomzzz

Reputation: 44598

why does pointer to array fails to return as **

I don't understand why the following fails:

#include<string>
class  Foo
{
  public:
     std::string** GetStr(){return str;}    

 private:
   std::string * str[10];
};

Thanks

Upvotes: 1

Views: 169

Answers (1)

jkeys
jkeys

Reputation: 3955

First, you tag this as C++ and C. Which is it? C does not have a string class. If it is C++, please remove the C tag, it is misleading (they are not the same language!).

Edit: I misunderstood what you are trying to do. Your method should compile. You just have to remember to dereference the returned str to get the string.

I rarely deal with double indirection, but you have to do something like this to set the string:

*(*str) = "STR"; //or
*(str[i]) = "STR";

I don't know how you would use the address operator here, because it returns a reference and not a pointer.

to set the string in the str array. Your method is really weird. The problem is that the compiler doesn't know that you want to dereference a string, so it tries to dereference a char*.

I do not understand why you want to do it this way, though. It would be better to do this:

std::string str[10];
std::string* GetStr() { return str; }

Upvotes: 1

Related Questions