Vidar Hasfjord
12/14/2008 12:12:00 AM
On Dec 13, 2:57 am, Abhayks <abhaysa...@gmail.com> wrote:
> On Dec 13, 10:13 am, Sam <s...@email-scan.com> wrote:
> > Abhayks writes:
> > [...]
> > > Please advise why this is not working?
>
> > 1) Operator precedence. [] carries higher precedence than the unary *
> > operator.
>
> > 2) The string must be zero-terminated. malloc does not clear allocated
> > memory.
>
> God! how can I miss it.
Maybe it would be just as well. There are better ways in C++ than
using pointers and manual memory handling. If you really did want to
return an array, as your subject title says, you can do it safely like
this:
typedef tr1::array <char, 255> Array;
Array foo () {
Array a = {'a', 'a', 'a', 'a', 'a'};
//strcpy (a.begin (), "Hello World");
return a;
}
int main () {
Array a = foo ();
cout << a.begin () << endl;
return 0;
}
But, of course, your example calls for std::string:
string foo () {
return "aaaaa"; // "Hello World";
}
int main () {
string s = foo ();
cout << s << endl;
return 0;
}
Regards,
Vidar Hasfjord