Answer the question
In order to leave comments, you need to log in
How to display an element of a two-dimensional array in a function?
Hello. Please tell me why the following code - a function for displaying an array element - does not work.
#include<iostream>
using namespace std;
int **transpose(const int *const *m, unsigned rows, unsigned cols);
void show(const int *const *m, unsigned rows, unsigned cols);
int main() {
int a[2][2] = {{1, 2},
{2, 1}};
cout << a[0][0];
show((const int *const *) a, 2, 2);
return 0;
}
void show(const int *const *m, unsigned rows, unsigned cols) {
cout << m[0][0];
}
Answer the question
In order to leave comments, you need to log in
Is it possible to cast int [][] const int *const *?
Declare an array like this
int n = 2;
int m = 2;
int** a = new int*[m];
for(int i = 0; i < n; ++i){
a[i] = new int[n]{1,2};
}
void show(const int *const *m, unsigned rows, unsigned cols)
{
for(int i=0; i<rows;++i){
for(int j=0; j<cols;++j){
cout << m[j+i*cols] << " ";
}
cout << endl;
}
}
Something like this: ideone.com/Q9hMqP
void show(const int *const *m, unsigned rows, unsigned cols) {
for (int i=0; i<rows; ++i) {
for (int j=0; j<rows; ++j) {
cout << m[i][j] << " | ";
}
cout << endl;
}
}
int main() {
const size_t ARRAY_SIZE = 2;
int a[ARRAY_SIZE][ARRAY_SIZE] =
{{1, 2},
{2, 1}};
int **b = new int*[ARRAY_SIZE];
for (int i=0; i<ARRAY_SIZE; ++i) {
b[i] = a[i];
}
show(b, ARRAY_SIZE, ARRAY_SIZE);
delete b;
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question