Student228 - 2 months ago 7x
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];
}

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

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";
}

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++,