I am trying to write a function which takes variable size array and prints it. But i am having problem in function declaration argument list while compiling.
The error is:
cannot convert ‘int (*)[(((sizetype)(((ssizetype)r) + -1)) + 1)]’ to ‘int**’ for argument ‘1’ to ‘void printHalf(int**, int, int)’
printHalf( b, r, r);
Code:
#include <iostream>
using namespace std;
void printHalf( int **a, int row, int col ) { // Problem is here.
for( int i=0; i < row; i++) {
for( int j=0; j < col; j++) {
if( i <= j) {
cout << a[i][j] << " ";
}
}
cout << endl;
}
}
int main() {
int r;
cout << "No. of rows: ";
cin >> r;
int b[r][r];
for( int i=0; i < r; i++) {
for( int j=0; j < r; j++) {
cin >> b[i][j];
}
}
printHalf( b, r, r);
return 0;
}
What is causing this error, and how do i pass various arrays to function?
Problems that I see
C++ does not allow declaration of variable length arrays. Hence,
int b[r][r];
is wrong.
A one dimensional array decays to a pointer but a two dimensional array does not decay to a pointer to pointer. Even if you had b
defined correctly, such as:
int b[10][10];
you cannot use b
as an argument to a function that expects an int**
.
Solution
I suggest use of std::vector
.
std::vector<std::vector<int>> b(r, std::vector<int>(r));
Change the function printHalf
accordingly.
void printHalf( std::vector<std::vector<int>> const& b ) { ... }
You don't need row
and col
as arguments since that information can be obtained from the std::vector
.
First off int b[r][r];
is a variable length array and is not standard in C++. If you need a container that can be sized at run time then I suggest you use a std::vector
std::vector<std::vector<int>> data(r, std::vector<int>(r, 0)); // create vector and set all elements to 0
Then your print function would become
void printHalf(const std::vector<std::vector<int>>& data) {
for( std::size_t i=0; i < data.size(); i++) {
for( std::size_t j=0; j < data[i].size(); j++) {
if( i <= j) {
cout << a[i][j] << " ";
}
}
cout << endl;
}
}
A 2D array of [N][M]
is laid out the same in memory as a 1D array of [N*M]
.
void printHalf( int *a, int row, int col ) { // Problem is here.
for( int i=0; i < row; i++) {
for( int j=0; j < col; j++) {
if( i <= j) {
cout << a[i*col+j] << " ";
}
}
cout << endl;
}
}
Then you can call it with printHalf( &b[0][0], r, r)
.
Your fundamental misunderstanding is the relationship between arrays and pointers. Arrays aren't pointers. An int**
can be viewed as an array of int*
, which isn't what you have. b[0]
gets you an int[r]
. This is different to an int*
. b[0][0]
gets you the first int
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.