D
D
Demigodd2018-04-08 11:49:11
C++ / C#
Demigodd, 2018-04-08 11:49:11

How to correctly pass a two-dimensional array to a function?

spoiler
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int size = 5;
int sum;

int prn(int sum) {
  std::cout << " = " << sum << "\n";
}

void foo(int arr[][size]) {
        int i = 0;
        while(i < size) {
            sum += arr[i][i];
            i++;
        }
        std::cout << "array:";
        prn(sum);
}

int main() {
    srand(time(NULL));
    
    std::cout << "Write the Length of the Array: ";
    std::cin >> size;
    
    int arr[size][size] = {};
    
     for(int i = 0; i < size; i++) {
            for(int j = 0; j < size; j++) {
                arr[i][j] = rand() % 10;
            }
        }
        
    foo(arr);
}

If you run it like this, then there will be an error.
but if you specify a specific number instead of size, then everything will work.
void foo(int arr[][5]) { ... }

int arr[5][5] = {};

How to send an array to a function in the first case? Tell me the best option.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2018-04-08
@Demigodd

const int size
Array is not passed. A pointer is passed. Even if you write a[][size]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question