Student228 Student228 - 4 months ago 18
C++ Question

Using two-dimensional massive in function C++

When I compile this code(below) it gives me an error:

prog.cpp: In function 'int main()':
prog.cpp:46:37: error: cannot convert 'int (*)[n]' to 'int**' for argument '4' to 'void dfs(int, std::vector<int>&, int, int**)'
dfs(1, used, n, Adjacency_matrix);


As I understand situation its because of calling two-dimensional massive in function uncorrectly. What i need to correct in this code so that function accepts my massive.

p.s. Sorry for my english :)

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>

void dfs(int i, std::vector <int> &used, int n, int (&Adjacency_matrix)[n][n]) {
used[i] = 1;
for (int j = 0; j < n; ++j) {
if ((Adjacency_matrix[i][j] == 1) && (used[j] == 0))
dfs(j, used, n, Adjacency_matrix);
}
}

double distance(int x1, int y1, int x2, int y2) {
return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
}

int main() {
int n, k;
std::cin >> n >> k;

int coordinates[n][2];

for (int i = 0; i < n; ++i) {
std::cin >> coordinates[i][1];
std::cin >> coordinates[i][2];
}

int Adjacency_matrix[n][n];

for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i == j)
Adjacency_matrix[i][i] = 0;
if ((i != j) && (distance(coordinates[i][1], coordinates[i][2], coordinates[j][1], coordinates[j][2]) <= k))
Adjacency_matrix[i][j] = 1;
if ((i != j) && (distance(coordinates[i][1], coordinates[i][2], coordinates[j][1], coordinates[j][2]) > k))
Adjacency_matrix[i][j] = 0;
}
}

std::vector <int> used;
for (int i = 0; i < n; ++i)
used.push_back(0);

dfs(1, used, n, Adjacency_matrix);
for (int i = 0; i < n; ++i) {
if (used[i] == 0)
std::cout << "NO";
exit(0);
}
std::cout << "YES";
}

Answer

Your dsf function declaration is wrong. Use

template<size_t N>
void dfs(int i, std::vector <int> &used, int (&Adjacency_matrix)[N][N]) 
{ ... }

to capture the size of the array passed by reference. Next, you cannot use variable sized arrays in standard C++,

int Adjacency_matrix[n][n]; 

is not valid, unless n is a const or constexpr. Hence, you cannot read it from cin. If you want dynamic size, use std::vector or pointers.