1

Possible Duplicate:
passing 2D array to function

My question is related to passing an array as a C++ function argument. Let me show the example first:

void fun(double (*projective)[3])
{
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
        {
            projective[i][j]= i*100+j;
        }
}

int main()
{
    double projective[3][3];     

    fun(projective);
    for(int i=0; i<3; i++)
    {
        cout<<endl;
        for(int j=0; j<3; j++)
            cout<<projective[i][j]<<"   ";
    }


    return 0;
}

In the example, the passing argument for fun is an array, and I was wondering whether there are other ways of passing this argument. Thanks!

Community
  • 1
  • 1
feelfree
  • 9,501
  • 18
  • 76
  • 143

3 Answers3

3

fun takes a pointer-to-array-of-3-double and it assumes (relying on the caller) that this points to the first element of an array of at least 3 arrays-of-3-doubles. Which it does, because as you say the argument supplied to the call in main is an array. This immediately decays to a pointer to its first element.

One alternative would be for fun to take a pointer-to-3x3-array-of-double, since it assumes that size anyway and the caller does in fact have such a beast:

void fun(double (*p_projective)[3][3])
{
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
        {
            (*p_projective)[i][j]= i*100+j;
        }
}

Call it with fun(&projective).

Steve Jessop
  • 257,525
  • 32
  • 431
  • 672
1

You cannot pass an array as such, it always decays to a pointer. But you can pass an array if you wrap in it a struct. This works in C and C++. In C++ you can pass a reference to an array. In both cases the array is fixed size.

// as a struct
struct Array
{
  int elems[10];
};

void func(Array a);

// as a reference
void func(int (&a)[10]);
john
  • 7,667
  • 24
  • 26
1

If you're so inclined, you can also just use a base pointer and do the offsets yourself, assuming your array was allocate or declared to have dim*dim elements.

void fun(double *projective, size_t dim)
{
    for(size_t i=0; i<dim; i++)
        for(size_t j=0; j<dim; j++)
            projective[i*dim+j] = i*100+j;
}

int main(int argc, char *argv[])
{
    double ar[5*5];
    fun(ar, 5);
    return 0;
}

There are a horde of ways to do this, this is only one, but usually the easiest to wrap my head around (and I usually use std::vector<> for the back-end).

WhozCraig
  • 59,130
  • 9
  • 69
  • 128