I have the following method signature:
int get_name(char* &name_out);
What I'd like to be able to do is allocate memory that is the size of name for name_out and then copy the contents of name into name_out.
Or would it be better to change it to:
int get_name(char &name_out[], int size);
and allow the user of the function to first allocate and track the memory, and return an error if the size of the given array isn't large enough to contain the string?
The only thing that I don't like about that is that it would require the user of the get_name() function to have knowledge about the length of the name string.
I feel it would be redundant to have two functions int get_name_length(); and get_name(char* name_out);
Since this is a piece of a programming assignment, there are stipulations:
- The string class is not allowed.
- C-style strings must be used.
- Vectors cannot be used.
- The function must return an int to indicate an error.
- Exception handling is not allowed.
Thank you.
The standard C way to do this, is to pass two pointers to the function:
This has several advantages:
The caller is free to preallocate memory/reuse an allocation.
The callee is free to adjust the allocation via
realloc()(assuming that the C-style string is allocated withmalloc()), or via a pair ofdelete[]/new[].The address taking is explicit. I.e. at the calling site you would write:
The explicit
&operator makes it very clear that the functiongetName()can change both variables. If you go with references, you cannot distinguish between call by reference and call by value without looking at the function declaration.Also note, the type to use for allocation sizes is
size_t: it is the type that is guaranteed to be able to hold the size of the entire usable address space.