Pages: [1]   Go Down
Author Topic: Returning an array from a function  (Read 250 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 1
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

How do I return an array from a function?

So far I have
Code:
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
Logged

Offline Offline
Jr. Member
**
Karma: 0
Posts: 57
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

Rome, Italy
Offline Offline
Sr. Member
****
Karma: 20
Posts: 442
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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
}
Logged

Pages: [1]   Go Up
Jump to: