0

How to return array in C?

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>

    int main()

    {
        int func(int);
        printf("%d",func(1));

    }

    int func(int n)
    {
        int i,arr[5]; //or int *arr=(int*)malloc(5);
        for (i=0; i<5; i++) {
            arr[i]=n++;
        }
        return arr;
    }

I want to get result '11111', but this code's result is '1606416336'.
What can I do to solve this problem?

8
  • 2
    You can't return a local array in C. You need to allocate it dynamically with malloc(). Commented May 5, 2015 at 0:14
  • tutorialspoint.com/cprogramming/… Commented May 5, 2015 at 0:15
  • eskimo.com/~scs/cclass/int/sx5.html Commented May 5, 2015 at 0:15
  • 1
    You can't ever return an array in C. It's an annoying limitation. You can, however, return a struct that contains an array, or have the caller create an array and pass a pointer to it as an argument. Commented May 5, 2015 at 0:15
  • int func(int n) { int i, v = 0; for (i=0; i<5; i++) { v = v * 10 + n; } return v; } Commented May 5, 2015 at 0:16

1 Answer 1

0
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int *func1(int);
    int func2(int);
    int *p = func1(1);
    int i;
    for(i=0; i < 5; ++i){
        printf("%d", p[i]);
    }
    printf("\n");
    free(p);

    printf("%d",func2(1));
    return 0;
}

int *func1(int n){
    int i;
    int *arr=(int*)malloc(5*sizeof(int));
    for (i=0; i<5; i++) {
        arr[i]=n;
    }
    return arr;
}

int func2(int n){
    int i, v = 0;
    for (i=0; i<5; i++){
        v = v * 10 + n;
    }
    return v;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.