P
P
parkito2016-05-19 22:49:32
C++ / C#
parkito, 2016-05-19 22:49:32

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];

}

The function, according to the condition of the problem, must accept const int * const * m .

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2016-05-19
@parkito

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

and everything will be fine

A
AtomKrieg, 2016-05-19
@AtomKrieg

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

F
Fat Lorrie, 2016-05-20
@Free_ze

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 question

Ask a Question

731 491 924 answers to any question