Using Pointers to Return an Array from a Function
This section examines data transfer in the opposite direction: returning an array from a function.
Strictly speaking, an array cannot be directly returned by a function. You can, however, have a function returning a pointer to anything you like, including an array. Remember, declaration follows use. An example declaration is:
int (*paf())[20];
//Here, paf is a function, returning a pointer to an array of 20 //integers. The definition might be:
int (*paf())[20] {
int (*pear)[20]; /* declare a pointer to 20-int
array */
pear = calloc( 20,sizeof(int)); if (!pear) longjmp(error, 1); return pear;
}
//You would call the function like this:
int (*result)[20]; array */
result = paf(); (*result)[3] = 12; Or wimp out, and use a struct:struct a_tag { int array[20];
/* declare a pointer to 20-int/* call the function */ /* access the resulting array */
} x,y;
struct a_tag my_function() { ... return y }
//which would also allow:
x=y; x=my_function();
//at the expense of having to use an extra selector x in accessing the elements:
x.array[i] = 38;
Sign up here with your email
ConversionConversion EmoticonEmoticon