Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A C function that returns a char array Vs a function working with 2 char arrays

Tags:

c

function

I'm a C beginner so my apologies if this doubt is too obvious.

What would be considered the most efficient way to solve this problem: Imagine that you have a char array ORIG and after working with it, you should have a new char array DEST. So, if I wanted to create a function for this goal, what would the best approach be:

  1. A function that takes only one char array parameter ( argument ORIG ) and returning a char array DEST or
  2. A void function that takes two char array arguments and does its job changing DEST as wished?

Thanks!

like image 298
pstrusi Avatar asked Dec 16 '25 20:12

pstrusi


2 Answers

This very much depends on the nature of your function.

In your first case, the function has to allocate storage for the result (or return a pointer to some static object, but this wouldn't be thread-safe). This can be the right thing to do, e.g. for a function that duplicates a string, like POSIX' strdup(). This also means the caller must use free() on the result when it is no longer needed.

The second case requires the caller to provide the storage. This is often the idiomatic way to do these things in C, because in this case, the caller could just write

char result[256];
func(result, "bla bla");

and therefore use an automatic object to hold the result. It also has the benefit that you can use the actual return value to signal errors.

Both are ways of valid ways of doing it, but I'd suggest using the latter, since it means you can load the contents into any block of memory, while a returned array will have to be on heap, and be freed by design. Again, both are valid ways of doing things, and this is just a guideline. What should be done usually depends on the situation.

like image 21
Shahe Ansar Avatar answered Dec 19 '25 09:12

Shahe Ansar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!