Whenever I deem possible, and after completing a given exercise from the two books I'm using to learn C++, I try to do the same thing but this time with pointers, arrays, c-style strings, and lots, lots, of consts.
I do this to try to consolidate my knowledge of these err... illusive constructs. However, I get this pervading feeling I could do it in a simpler way while still using the C style code. Maybe I can blame my Visual Basic background, and it's overly high-level nature, for this...
This is one of those moments. The following function is my solution to one of the exercises found on C++ Primer 4th Edition. Basically, a minimalist solution to output the plural of a word.
I would like you to comment on two things, if possible:
1. Did I complicate things unecessarily by using strncpy() and strncat()? Is there a simpler solution?
2. The dnamic c-string was the only way I found to be able to produce an array that can obviously only know its size at run-time. Had I choose not to create it dynamically, but instead fixed, would there be another solution other than passing the size of both strings as arguments to the function?
Code:const char* plural(const char* word, const char* pls = "s") { char* ret = new char[strlen(word) + strlen(pls) + 1]; strncpy(ret, word, strlen(word) + 1); strncat(ret, pls, strlen(pls) + 1); return ret; }