Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an array return type from C function?

Tags:

c

I have tried to return the array name as shown below. Basically I am trying to make the function test return an array that can be used in main. Could you advise me as to what I need to read into more to find out how to perform a function like this?

#include <stdio.h>

int test(int size, int x){
    int factorFunction[size];    
    factorFunction[0] = 5 + x;
    factorFunction[1] = 7 + x;
    factorFunction[2] = 9 + x;
    return factorFunction;
}

int main(void){
    int factors[2];
    factors = test(2, 3);
    printf("%d", factors[1]);
    return 0;
}

I receive the compiler errors:

smallestMultiple.c:8: warning: return makes integer from pointer without a cast
smallestMultiple.c:8: warning: function returns address of local variable
smallestMultiple.c: In function ‘main’:
smallestMultiple.c:13: error: incompatible types in assignment
like image 788
user1530249 Avatar asked Jan 12 '13 19:01

user1530249


People also ask

Can an array be a return type?

A method can return a reference to an array. The return type of a method must be declared as an array of the correct data type.

What is * array [] in C?

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To create an array, define the data type (like int ) and specify the name of the array followed by square brackets [].

How do you return an array of structures?

You can't return arrays from functions — period. You can return pointers though, provided the storage will continue to exist after the function returns. Or you can pass a pointer to the function pointing to the storage that the function should use. Don't forget to pass the size of the array too.


1 Answers

Functions can't return arrays in C.

However, they can return structs. And structs can contain arrays...

like image 200
Oliver Charlesworth Avatar answered Sep 28 '22 08:09

Oliver Charlesworth