Passing a 2d array into a function?

Dec 12, 2016 at 10:36am
Basically I am wondering how its possible to pass an array through a function so that its values can be changed via another function without using global variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void mainArray();

int main()
{
  while(condition = true)
   {
      mainArray();
      editArray(); //This is a function that I would want to use to edit mainArray()
   }
}

void mainArray()
{
char myArray[3][3] = { { '20','15','26' } ,{ '31','32','50' } ,{ '16','27','86' }};
cout << myArray[blah][blah]; 
}


I want to able to use editArray to change the data in myArray and then have the screen refreshed with the updated data.
Last edited on Dec 12, 2016 at 10:37am
Dec 12, 2016 at 10:41am
You just pass the array in the function using * array[col size]

Dec 12, 2016 at 10:53am
So would it basically be smarter to just pass the array through to the function from Main()?
Dec 13, 2016 at 7:48am
Statically declared 2D array:
1
2
3
4
5
6
7
8
9
10
const int COLUMNS{ 3 };
void print_array( int arr[][COLUMNS], int rows )
{
    for( int r{}; r < rows; r++ ) {
        for( int c{}; c < COLUMNS; c++ )
            std::cout << arr[r][c] << ' ';
        
        std::cout << '\n';
    }
}

1
2
3
4
5
6
7
8
9
10
template<int rows, int cols>
void print_array( int (&arr)[rows][cols] )
{
    for( int r{}; r < rows; r++ ) {
        for( int c{}; c < cols; c++ )
            std::cout << arr[r][c] << ' ';
        
        std::cout << '\n';
    }
}


Dynamically declared 2D array:
1
2
3
4
5
6
7
8
9
void print_array( int** arr, int rows, int cols )
{
    for( int r{}; r < rows; r++ ) {
        for( int c{}; c < cols; c++ )
            std::cout << arr[r][c] << ' ';
        
        std::cout << '\n';
    }
}
Topic archived. No new replies allowed.