Go Down

Topic: Returning an array from a function (Read 279 times) previous topic - next topic

How do I return an array from a function?

So far I have
Code: [Select]

double MatMatDot(double a[3][3], double b[3][3])[3][3]
{
return {{1.0,0.0,0.0},{0.0,1.0,0.0},{0.0,0.0,1.0}};
}


but I get the error  " 'MatMatDot' declared as a function returning an array"

-Shane

eriknyquist

You can't, is the short answer. I don't know much about the subject myself but a google search revealed this article as the top result, which provides some workarounds.
http://www.eskimo.com/~scs/cclass/int/sx5.html

spatula

In terms of syntax you could return a pointer to the array, but then you would need to ensure that the pointer is still valid when you exit the function. In other words, if you create an array inside the function its memory will be freed when the function returns. There are ways to circumvent this, e.g. you can call malloc(), return the pointer, and then free the memory when you are done with it.

A simpler way is to pass the array as an argument to the function:
Code: [Select]

void MatMatDot(double dest[3][3], double a[3][3], double b[3][3])
{
// use dest as the output of your function, don't need to return anything
}

Go Up