I am having trouble with the basic principles of strings in C.
I have a function:
char *editStr(char *str) {
char new[strlen(str)];
... do some editing ...
return new;
}
How would I return the array of characters called “new”. As I understand, the return value of the function is a char*, which means that it is asking for a pointer to the first character of a string.
Right now, I guess the problem is that I am returning a character of arrays. I tried to return a pointer to the first character in “new”, but that doesn’t seem to work, either.
I tried “return *new[0]”.
My string knowledge is bad.
There are various problems here but the array/pointer issue with
return new;isn’t one of them.First, you want:
So that you have enough room for the null terminator.
Your
newis allocated on the stack so returning it will only cause grief and confusion; you’ll want to:instead so that the memory is still valid when the function returns.
As far as your real question goes, an array in C is the address of the first element so your
return new;is fine (subject to the stack versus heap issue noted above). C arrays decay to pointers at the drop of a hat so you don’t need to worry about returning an array when the function is declared to return a pointer.