Passing and Returning C strings

Hello, I am familiar with C++ but I have to write a function in c. I have to take a null pointed string and return it reversed. Seems simple enough my question is on returning the c-string.

What is the proper way to do this? "new-up" a string and return a pointer to that string? Take in another pointer in and point it with the reversed version? Or change the original pointed string? Or is it a matter of preference?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  char* rev(char* p){
//create new string
//do rev
return newString
}

//or
char* rev(char* p, char *result){
}

char* rev(char* p){
//re point the string?
}

Last edited on
It really depends on how the requirement is stated.

If the requirement says "reverse a C-string", I would take that to mean reverse it in place. No need or expectation of a second string. The algorithm is a little trickier that using a second string, but not difficult.

If the requirement says "take a C-string and return a new string which is the reverse of it", then a second string is clearly called for. In this case the algorithm is trivial.

Your option #1 requires the caller to release the newly allocated string. Possibility for memory leaks. So not the best choice.

Your option #2, places the burden of providing the second C-string on the caller. Avoids the possibility of memory leaks, but more work for the caller.

Your option #3, I presume is reversing in place (one string). Not sure what you mean by "repointing the string". You can return p as a convenience to the caller, but that's not necessary. This option is the most straightforward for the caller.


Thank you much. Its a big help!
Topic archived. No new replies allowed.