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:
Thank you.
The standard C way to do this, is to pass two pointers to the function:
int getName(char** name_out, size_t* size_out);
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 with malloc()
), or via a pair of delete[]
/new[]
.
The address taking is explicit. I.e. at the calling site you would write:
char* name = null_ptr;
size_t size = 0;
if(getName(&name, &size)) handleError();
The explicit &
operator makes it very clear that the function getName()
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.