hi everyone,i'm a c++ beginner,i have a very simple question...
how can i let function return an char string array??
char aa[10]="asdfghj";
//function...body
return(aa);
is this true???
hi everyone,i'm a c++ beginner,i have a very simple question...
how can i let function return an char string array??
char aa[10]="asdfghj";
//function...body
return(aa);
is this true???
return aa[10];
edit: though it depends, do you want it to return just one piece of the string, or the entire thing. Entirety is above.
Assuming that array isn't a local variable, you can do this:
But if the array is a local variable (declared in the function that returns it), you can't return it because the memory is released when the function returns. Since you're returning a pointer to the memory, and the memory no longer belongs to you after returning, you'll usually get nothing but garbage and undefined behavior:Code:char *function() { ... return aa; }
It's almost always better to use the std::string class supported by C++ instead of low level C strings. There's less trouble.Code:char *function() { char aa[10]; return aa; // Very bad! }
>return aa[10];
This won't work. You're accessing only a single item in the array with the subscript operator, but since the subscript you give is the size of the array, you're accessing out of bounds. This too is undefined behavior.
My best code is written with the delete key.
You could also pass a variable as a parameter of the function that will take the value.
if you want the function to modify the string, its best to pass the string in as a pointer. an array without the brackets acts as the address of the first variable in that array.
for example, here is how you would make a function that accepts a string.
Code:void function( char * array, int size ); /* always good to pass the size of your array*/ int main() { char array[10] = "abcdefghi"; function( array, 10 ); return 0; } void function( char * array, int size ) { array[1] = //modify string }
when you pass it as a pointer, its kind of as if the scope of that array was extended to that function, and the function modifies it directly, rather than just returning a copy of it. also, thats the only true way to return an entire array from a function.
Last edited by ...; 07-31-2003 at 11:47 AM.
I came up with a cool phrase to put down here, but i forgot it...