Second what dwhitney said.
If you do want to make it return "const char *", I'd consider making str static and returning a pointer to it, which eliminates the possibility of a memory leak as well as simplifying the code.
Code:
const char *char2str(char ch)
{
static char str[2] = {0};
str[0] = ch;
return str;
}
This works because str has static storage duration, which means its contents don't become indeterminate when char2str returns and the name goes out of scope. Since there's only one copy of it, though, you will lose information if you call char2str multiple times in a row:
Code:
const char *s1, *s2;
s1 = char2str('a');
s2 = char2str('b');
puts(s1);
puts(s2);
This will print "b" twice because the second call to char2str overwrites the "a" that was already in str. For a short and simple program like yours this doesn't make a difference.
Another, idiomatic alternative is passing char2str a pointer to the string it is to modify. In this case I'd definitely leave off the const:
Code:
char *char2str(char *str, char ch)
{
str[0] = ch;
str[1] = 0;
return str;
}
I'd prefer one of these over your solution or Bachstelze's because I'm allergic to dynamic memory, and I especially try to ensure that a *alloc() and its corresponding free() are always found in the same function (preferably within a few lines of each other). When I have to return a pointer to dynamically allocated memory, I name the function something ending in 'alloc' to remind me to free() the pointer it returns.
Bookmarks