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
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.
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 [].
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.
Functions can't return arrays in C.
However, they can return structs. And structs can contain arrays...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With