Re: Problem with char* as a parameter
"Neil" <nillugb@gmail.com> wrote in message
news:1181577401.253717.268220@q75g2000hsh.googlegroups.com...
I am working on a code that is supposed to return a string to my main
function from the test function. The cout in test returns "My Name",
but the cout in main returns some junk characters.
Can anyone tell me how I could fix it so I get "My Name" printed from
main also. Thanks.
#include <iostream>
using namespace std;
void test (char * temp[])
{
char name[] = "My Name";
temp[0] = name;
cout << temp[0] << endl;
}
int main ()
{
char* info[9];
test (info);
cout << info[0] << endl;
}
Making char name[] to static char name[] solves your immediate problem as
then name doesn't go out of scope.
See if you can determine why the following does the same thing:
#include <iostream>
void test (char **temp)
{
char* name = "My Name";
*temp = name;
std::cout << temp[0] << std::endl;
}
int main ()
{
char* info;
test (&info);
std::cout << info << std::endl;
}
To help you out, you declared info as an array of 9 pointers to character.
That is, you could of had 9 different names it was pointing to. To store
the address of where "My Name" is only requires one pointer.
Of course there is the more C++ way using functions:
#include <iostream>
#include <string>
void test (std::string& temp)
{
char* name = "My Name";
temp = name;
std::cout << temp << std::endl;
}
int main ()
{
std::string info;
test (info);
std::cout << info << std::endl;
}
Note: In the first version I could of declared the function as char *& (a
reference to a character pointer) but since I think you're trying to
understand points I left it as a pointer.