Csharp_learner
Csharp_learner

Reputation: 341

How to pass a two dimensional array to a function in c++

I am trying to pass an array (2d) to a function as an parameter. I have a code as follows:

int main()
 {
  float T[100][100];
  void set_T(float T[][]);
}


void set_T(float T1[][])
{


  for (int i =0 ; i<90;i++)
  {
      for(int j =0 ;j <90;j++)
      {
          T1[i][j] = 3;
      }
  }

}

I am not sure how to pass array to a function ...I am getting lot of errors. Can any one help please.

Upvotes: 5

Views: 18080

Answers (3)

Chris Dodd
Chris Dodd

Reputation: 126517

There are two issues here:

  • C does not support 2D arrays, only arrays of arrays or arrays of pointers to arrays, neither of which is quite the same thing as a 2D array
  • C does not allow passing arrays to functions as arguments, only pointers into arrays (generaly, you use a pointer to an array's 0th element, since that's what the array's name ends up being so indexing off of such a pointer looks just like an array access)

So because of the first problem, you have to decide how you're going to represent a 2D array -- either an array of arrays, or an array of pointers to arrays. If you go the first route, your code ends up looking like:

void set_T(float (*T1)[100]) {
    ... do stuff with T1[i][j] ...
}

int main() {
    float T[100][100];
    set_T(T);
}

Here, you've declared T to be an array of 100 arrays of 100 floats, and set_T takes a pointer to arrays of 100 floats as its argument. You pass 'T' directly to set_T, as the language treats array names as pointers to their 0th element.

If instead you want to use an array of pointers to arrays, you end up with something like:

void set_T(float **T1) {
    ... do stuff with T1[i][j] ...
}

int main() {
    float *T[100];
    float space[100*100];
    for (int i = 0; i < 100; i++)
        T[i] = space + i*100;
    set_T(T);
}

The disadvantage here is that you need to allocate space for all of the second-level arrays and manually initialize all the first-level pointers to point at them. The advangtage is that the sizes of the second level arrays is not part of the type of the argument passed to set_T, so you can more easily deal with variable-sized arrays.

Of course, if you're really using C++ and not C, you should not be using C arrays at all -- you should be using std::vector or std::array instead -- both of which share the C array 1D only issue, so you need a vector of vectors or an array of arrays (or conceivably a vector of arrays or an array of vectors)

Upvotes: 8

Anycorn
Anycorn

Reputation: 51565

  void set_T(float (&T)[100][100]);

Upvotes: 6

Andrew Cooper
Andrew Cooper

Reputation: 32596

Just call it like this:

int main ()
{
    float T[100][100];
    set_T(T);
}

And as @suddnely_me said, the type of T1 in the function declaration need to be float**.

Upvotes: -4

Related Questions