4

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!

8
  • 7
    A pointer solution is precisely the answer you are looking for. Please elaborate why this is not appropriate. Commented Mar 10, 2010 at 10:29
  • c-faq.com/~scs/cclass/int/sx5.html Commented Mar 10, 2010 at 10:33
  • 6
    dont be afraid of pointer son. It will become your friend in no time. :) Commented Mar 10, 2010 at 10:33
  • 1
    In memory array also is a pointer. So you can return only one memory from the function. If you return array also it will return only first location of that array. Commented Mar 10, 2010 at 10:36
  • 1
    if you don't want to work with pointers you picked the wrong language Kosta. Almost all the cool stuff that C can do is with pointers. Commented Mar 10, 2010 at 11:03

5 Answers 5

11

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

You're missing a semicolon (and a 't').
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.
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
5

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.

Comments

4

C functions cannot return array types. Function return types can be anything other than "array of T" or "function returning T". Note also that you cannot assign array types; i.e., code like the following won't work:

int a[10];
a = foo();

Arrays in C are treated differently than other types; in most contexts, the type of an array expression is implicitly converted ("decays") from "N-element array of T" to "pointer to T", and its value is set to point to the first element in the array. The exceptions to this rule are when the array expression is an operand of either the sizeof or address-of (&) operators, or when the expression is a string literal being used to initialize another array in a declaration.

Given the declaration

T a[N];

for any type T, then the following are true:

Expression     Type      Decays to      Notes
----------     ----      ---------      -----
         a     T [N]     T *            Value is address of first element
        &a     T (*)[N]  n/a            Value is address of array (which
                                          is the same as the address of the
                                          first element, but the types are
                                          different)
  sizeof a     size_t    n/a            Number of bytes (chars) in array = 
                                          N * sizeof(T)
sizeof a[i]    size_t    n/a            Number of bytes in single element = 
                                          sizeof(T)
       a[i]    T         n/a            Value of i'th element
      &a[i]    T *       n/a            Address of i'th element

Because of the implicit conversion rule, when you pass an array argument to a function, what the function receives is a pointer value, not an array value:

int a[10];
...
foo(a);
...

void foo(int *a)
{
  // do something with a
}

Note also that doing something like

int *foo(void)
{
  int arr[N];
  ...
  return arr;
}

doesn't work; one the function exits, the array arr technically no longer exists, and its contents may be overwritten before you get a chance to use it.

If you are not dynamically allocating buffers, your best bet is to pass the arrays you want to modify as arguments to the function, along with their size (since the function only receives a pointer value, it cannot tell how big the array is):

int a[10];
init(a, sizeof a / sizeof a[0]);  // divide the total number of bytes in 
...                               // in the array by the number of bytes
void init(int *a, size_t len)     // a single element to get the number
{                                 // of elements
  size_t i;
  for (i = 0; i < len; i++)
    a[i] = i;
}

Comments

3

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

2 Comments

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

A Very very basic code and very very basic explanation HOW TO Return array back from a user defined function to main function..Hope It helps!! Below I have given complete code to make any one understand how exactly it works? :) :)

#include<iostream>
using namespace std;

char * function_Random()
{
    int i;
    char arr[2];
    char j=65;//an ascII value 65=A and 66=B
    cout<<"We are Inside FunctionRandom"<<endl;
    for(i=0;i<2;i++)
    {
        arr[i]=j++;// first arr[0]=65=A and then 66=B
        cout<<"\t"<<arr[i];
    }
    cout<<endl<<endl;
    return arr;
}
int main()
{

    char *arrptr;
    arrptr=function_Random();
    cout<<"We are Inside Main"<<endl;
    for(int j=0;j<2;j++)
    {
        cout<<"\t"<<arrptr[j];
    }
    return 0;
}

1 Comment

The program has undefined behavior, you are returning a pointer to a local object that gets destructed immediately, any use of arrptr in main is undefined behavior.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.