David said:
However if You need to return a string value without using the string
library, you either need to return a pointer to a string that was
allocated on the heap with malloc; ie:
char * somefunc()
{
char * tmp = malloc(100);
tmp = "hello world\0";
return tmp;
};
Here you see what happens if you try to do C style string handling without
knowing every detail about memory handling, arrays and pointers. The above
function leaks memory. First, 100 bytes are allocated, and that memory
block's address is stored in tmp. In the next line, the pointer tmp gets
overwritten by the address of the string literal "hello world\0" (btw:
String literals already have a terminating \0 character. No need to
explicitly add a second one). Since there is no pointer anymore to the
dynamically allocated block of memory, that memory is lost forever. Now the
address of the string literal is returned. That part is ok, because string
literals have static storage duration. However, you returned a pointer to
non-const, and the literal is actually constant. An attempt to write to it
results in undefined behavior. Attempting to delete it, too.
What you should actually have done is use the strcpy function to copy the
string literal's content over to the dynamic memory (and document in red
uppercase letters that the user of the function is responsible for deleting
the memory).
or you need to pass the function a string by reference and return the
result in that.
void somefunc(char *tmp)
{
tmp = "Hello World!\0";
}
Well, this function is actually a no-op. tmp is a local pointer. You
overwrite this pointer, then the function returns. The local pointer is
destroyed, and nothing outside the function has changed. Again, you should
have used strcpy.
main() must return int.
That would have to be:
char Str[100];
And that:
somefunc(Str);
I'm sorry, but you must either have been drunk when you wrote that or you
shouldn't give advice about pointers and arrays in C++.