# [geeks] [4][4] matrix

S. Gwizdak wazm at rm-f.net
Tue Feb 26 17:39:29 CST 2002

```> float t[4][4];
> t=myFunc();
> What is the proper way to declare myFunc so that the above would work
> properly?  More importantly, what book or web site would one go looking up
> such on?  All my c and C++ books gloss over such things since they were meant
> for freshmen.

Strictly speaking, an array cannot be directly returned by a function. You can
have the function returning to a pointer to anything you like, including an
array.

Let's say we have t[4] instead of t[4][4]...

int (*foo()) [4] {
int (*t)[4];
t = (int *) malloc(4*sizeof(int));
if (!t) exit(1);
return t;
}

int main() {
int (*t)[4];
t = foo();
(*t)[2] = 3;
}

As you can see, this gets ugly quick.

The clean solution is to do this:

struct foo {
float t[4][4];
} bar, blah;

struct foo this_function() {
...
return bar;
}

Then you can do wonderful things like: blah = bar and bar = this_function();

Now, alternatively, you can just pass the multidimensional array into a
function:

void this_function(float t[][4]);

You can use an Iliffe vector, which is create one-dimensional array of pointers
to something else.

void this_function(float **t);

But you can only do this if you change the two-dimensional array into an
array of pointers to vectors, so the first method is less bug prone. Typically
the second method will be used only with array of pointers, and only pointers
to strings. (You get out of bound markers for free.) So if you do it this way
with your floats, you'll need to provide some sort of counting mechanism.

void this_function(float t[][4]) {
t[1][1] = 2.3;
}

int main() {
float t[4][4];
this_function(t);

printf("%f\n", t[1][1]);
}

This prints out 2.30000. This is the mechanism of choice for doing
what you want.

```