views:

95

answers:

4

C++: Using and returning character arrays from functions, return type or reference? I'm trying to create a null terminated string outside of a function, then run a function which will assign some data to it. For example, char abc [80] is created in main. input() is then run, which will return user input to abc. I figure the two obvious ways to do this are:

1. Make the input function return the input to a variable in main, something like:

char input ()
{
    char input [80];
    getline(cin, choice);
    return input;
}

int main ()
{
    char choice [80];
    choice = input ();
    ...
}

2. Pass a character array to the input function my reference, and then put the data in it from there:

...
void input (&variable)
{
    getline(*variable, cin);
    return;
}
int main ()
{
    char choice [80];
    char* pointer;
    input (pointer);
    ...
}

But, I can't get either of these ways to work. So, what am I doing wrong and how can I fix it?

+6  A: 

Just use standard strings. The insanity of using arrays of constant width has caused at least the company I work four many hundreds of thousands of dollars in development time. The correct answer to you question may be frustrating to you but it really is, "DON'T DO THAT!!!"

Noah Roberts
Thanks. After looking through some examples I think you're right, std::string is the way to go. I'll just use that.
JBenson
Then please mark his reply as the answer.
C Johnson
A: 

Listen to Noah, but FYI what you're doing wrong is that you need to pass in a pointer to a pointer (char** variable).

Karl Bielefeldt
This is only true if you're allocating a new char array as part of the function. For writing into a user-provided string, you only need a pointer to the start and the length. (See e.g., scanf(3).)
Jack Kelly
+2  A: 

In the first method you are trying to return a char not a pointer to a char. C++ STL provides a string class that encapsulates character arrays in a much more reliable way. Granted raw character arrays are faster, but correctness is more important than performance.

std::string input()
{
    return std::string("return value");
}

int main()
{
    std::string myString = input();
}
Novikov
That's not really equivalent to OPs question. You should pass in a reference to the string to input()
Falmarri
I don't think passing in non-const references is a pattern that belongs in high level programming.
Novikov
A: 

In example 1 the variable input (I think you meant choice) is on the stack and is goes away when the function ends, you can't use that memory location in the calling function safely.

In example 2 you're passing a single character pointer, to get what you want to work you'll need to pass in a pointer to the choice array.

char ** pointer = choice;

and you won't want to derefernce variable in the input function, getline is expecting a double character pointer.

Actually gnu getline is expecting 3 parameters, but maybe you're not using that one.

Neth