The problem in your code is that your code returns a character, instead of the pointer to it. The return type of the function suggests that the function returns a character. Hence, you need to revise its signature into char *copyStr(const char *str)
.
Another problem is that the return value dereferences the pointer newStr
, making it return the value pointed by newStr
at the very end of the execution of the function. You need to return newStr
instead of *newStr
.
Also, this might not affect the result of the function, but the one point I want to point out is that the delete
statement after the return
statement has no effect. Moreover, since according to the description about the function, the caller will use the C-string returned by the function. Deleting it would make it impossible.
In conclusion, the revised version of the code will be like...
char* copyStr(const char* str)
{
char* newStr = new char(20);
for (; *str != '\0'; ++str)
{
*newStr = *str;
}
return newStr;
}
I also want to suggest to make the function take the length of the str
as additional input, and dynamically allocate a memory space according to the length - which can be ignored if you assume that the input string will be less than 20 bytes in its size.