tags:

views:

246

answers:

4

Hello,

I would like to know if there is any way to return an char array. I tried something like this "char[] fun()" but I am getting error.

I don't want a pointer solution. Thanks!

+2  A: 

arrays aren't 1st class objects in C, you have to deal with them via pointers, if the array is created in your function you will also have to ensure its on the heap and the caller cleans up the memory

jk
i guess he is new to C, he wont probably understand 1st class objects and heap :)
N 1.1
possible not, but then they know what answer to ask/search for next!
jk
+2  A: 

Arrays cannot be passed or returned by value in C.

You will need to either accept a pointer and a size for a buffer to store your results, or you will have to return a different type, such as a pointer. The former is often preferred, but doesn't always fit.

Roger Pate
+7  A: 

You can return an array by wrapping it in a struct:

struct S {
   char a[100];
};

struct S f() {
    struct S s;
    strcpy( s.a, "foobar" );
    return s;
}
anon
Nice move! Niel
abubacker
You're missing a semicolon (and a 't').
Bertrand Marron
@tusbar Thanks, fixed it.
anon
you can make life easier with `typedef struct S { char a[100] } T;` and then in place of `struct S` you can just write `T`.
Ninefingers
this can work but it's important for the poster to realize that a pointer and an array are pretty much the same thing in C
jsn
+2  A: 
John Bode