Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function with return type array in C

Tags:

arrays

c

I have the following function in C:

int[] function(int a){
    int * var = (int*)malloc(sizeof(int)*tags);
    ....
}

*var is it a pointer to an array var?

If yes, how can I return the array (var) in the function?

like image 959
holy Avatar asked Apr 03 '12 14:04

holy


2 Answers

You can't really return an array from a function, but a pointer:

int * function(int a){
    int * var = malloc(sizeof(int)*tags);
    //....
    return var;
}
like image 141
MByD Avatar answered Oct 26 '22 09:10

MByD


This code below could clarify a bit how array and pointers works. The function will allocate memory for "tags" int variables, then it will initialize each element with a number and return the memory segment that points to the array. From the main function we will cycle and print the array element, then we will free the no longer needed memory.

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

int *function(unsigned int tags) {
        int i;
        int *var = malloc(sizeof(int)*tags);

        for (i=0; i < tags; i++) {
                var[i] = i;
        }

        return var;
}

int main() {
        int *x;
        int i;

        x = function(10);
        for (i=0; i < 10; i++) {
                printf("TEST: %i\n", x[i]);
        }

        free(x); x=NULL;

        return 0;
}
like image 35
dAm2K Avatar answered Oct 26 '22 09:10

dAm2K