Question:

How do I send a 2D array into a function in C ?

by  |  earlier

0 LIKES UnLike

I need to send a 2D array into a function. I've seen it done with the command std::vector or something like that, but i have not learned that yet. Is there a way to do it using just a regular call by reference? Everytime I try to do that I get an error. Could someone please write a small sample code of how to send a 2D array into a function (without using std::vector -- if possible)

 Tags:

   Report

1 ANSWERS


  1. Array is passed by pointer, not by value. You must pass length of first dimension as an additional parameter and type array size of all other dimensions starting from second:

    base_type[][depth]...

    For example:

    #include <cstdlib>

    #include <iostream>

    void passArray(int a[][2], int length) {

      for (int i=0; i<length; i++) {

        std::cout << "{";

        for (int j=0; j<2; j++) {

          std::cout << a[i][j];

          if (j<1) std::cout << ",";

          

        }

        std::cout << "}";    

      }    

    }

    int main(int argc, char *argv[])

    {

        int b=2;

        

        int a[3][2]={{0,0},{1,2},{1,4}};

        passArray(a,3);

        

        system("PAUSE");

        return EXIT_SUCCESS;

    }

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.