Given below is my main() function:
int main()
{
int N = 4;
int A[N][N] = {
{1 , 0 , 0 , 0},
{1 , 1 , 0 , 1},
{0 , 1 , 0 , 0},
{1 , 1 , 1 , 1}
};
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
cout << A[i][j] << " ";
cout << "\n";
}
cout << "\n";
printSolution(N , *A);
cout << "\n";
return 0;
}
Here I had declared a 4x4 array with values. Given below is printSolution where I am passing a pointer to the array inside it.
void printSolution(int N , int *sol)
{
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
cout << *((sol + i) + j) << " ";
cout << "\n";
}
}
Given below is the output:
1 0 0 0
1 1 0 1
0 1 0 0
1 1 1 1
1 0 0 0
0 0 0 1
0 0 1 1
0 1 1 0
As it is visible in the output, the for loop inside the main function printed the array correctly, whereas the printSolution() function could not print it properly. Why is that so?
<array>or<vector>.int A[N][N]is not a valid declaration sinceNis not a constant expression. Many compilers allow it anyway as an unofficial extension called "variable length arrays", but those can bite you in tricky ways. Useconstexpr int N = 4;(orconst int N = 4;) instead.