How to return array inside a function?

I have written this simple algorithm to return an array from a function when and array is add as the input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  #include<stdio.h>


int** add(int A[2][2],int m)
{
    int B[2][2],i,j;
    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 2; j++)
        {
            B[i][j]=A[i][j]+m;            
    }
    }
    return B;
}

int main(void){
int A[2][2]={{3,1},{2,0}},m=9,Z[2][2];
Z=add(A,m);
return 0;
}
When dealing with straight-arrays, don't return them. Use a reference argument:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>

void add(int result[2][2],int A[2][2],int m)
{
    int i, j;
    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 2; j++)
        {
            result[i][j] = A[i][j] + m;
        }
    }
}

void print( int A[2][2] )
{
    int i, j;
    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 2; j++)
        {
            printf( "%d ", A[i][j] );
        }
        printf( "\n" );
    }
}

int main()
{
    int A[2][2] =
    {
        { 3, 1 },
        { 2, 0 }
    };
    int m = 9;
    int Z[2][2] = {{0}};

    add( Z, A, m );

    print( Z );

    return 0;
}

Hope this helps.
Please forgive a layman, but, although it works, I do not understand how the result in add() is passed back to the array Z. I thought you'd have to pass the value by reference or return the values, but in Duoas' example the function returns void and Z is the array being passed (by value?) unless there is a -- to me -- hidden mechanism that changes "by value" to "by reference" for arrays...
Could somebody please be so kind and either explain what happens, or point me to a place that explains the reason it works?
I would really appreciate that. Thanks

Edit: found my own answer in
http://www.cplusplus.com/doc/tutorial/pointers/#arrays
and
http://www.cplusplus.com/doc/tutorial/arrays/#arrayparameters
Last edited on
Topic archived. No new replies allowed.