Home > Blockchain >  Issue with c referencing to function with 2d array
Issue with c referencing to function with 2d array

Time:03-12

I'm trying to get this matrix and print it out in the another function. The problem is that is impossible. I tried to solve it with ** and * but I got only the adress not the value but I cannot get the normal values as this in matrix 5x5. Can someone explain me what I do in a wrong way?

size_t matrix[5][5] =
    {
        {1, 16, 20, 23, 25},
        {6, 2, 17, 21, 24},
        {10, 7, 3, 18, 22},
        {13, 11, 8, 4, 19},
        {15, 14, 12, 9, 5},
    };
    set<bool> set1 = iterateover((size_t**)matrix)
     std::set<bool> iterateover(size_t** array)
    size_t numberofrows = sizeof(**arrayy) / sizeof(arrayy[0]);
    size_t numberofkols = sizeof(*arrayy[0]) / sizeof(arrayy[0][0]);
    std::set < bool >myset;
    for (size_t i = 0; i < numberofrows; i  )
    {
        for (size_t j = 0; j < numberofkols; j  )
        {
            std::cout << arrayy[i][j] << std::endl;
    return myset;

CodePudding user response:

you get row, col number incorrectly,it should be like this:

   size_t numberofrows =
        sizeof(matrix) / sizeof(matrix[0]);

    size_t numberofcols = sizeof(matrix[0]) / sizeof(matrix[0][0]);

and you want to print out to other function lets use template

template <typename T>
void print_matrix(T matrix, int numberofcols, int numberofrows)
{
    for (size_t i = 0; i < numberofrows; i  ) {
        for (size_t j = 0; j < numberofcols; j  ) {
            std::cout << matrix[i][j] <<" ";
        }
        std::cout << "\n";
    }
}

tested at : https://godbolt.org/z/vshev1e17

CodePudding user response:

if u want to define it in fun and print it in another function u need to do it dynamic not static or u can define it globally and access it from any function u defined check this Return a 2d array from a function

CodePudding user response:

You can make iteratreOver a function template which can take a 2D array by reference, as shown below.

#include <iostream>
template<typename T,std::size_t N, std::size_t M>
void iterateOver(T (&arr)[N][M])
{
    for(std::size_t i= 0; i < N;   i)
    {
        for(std::size_t j = 0; j < M;   j)
        {
            std::cout<<arr[i][j] <<" ";
        }
        std::cout<<std::endl;
    }
}
int main()
{
    size_t matrix[5][5] =
    {
        {1, 16, 20, 23, 25},
        {6, 2, 17, 21, 24},
        {10, 7, 3, 18, 22},
        {13, 11, 8, 4, 19},
        {15, 14, 12, 9, 5},
    };
    //call iterateOver by passing the matrix by reference
    iterateOver(matrix);
   
}

The output of the above program can be seen here:

1 16 20 23 25 
6 2 17 21 24 
10 7 3 18 22 
13 11 8 4 19 
15 14 12 9 5
  • Related