`int (*q)[m][n]=( int(*)[m][n] )p;` 这种类型转换是否可能,其中 p 是指向矩阵基地址的普通整数指针 `int *p`

`int (*q)[m][n]=( int(*)[m][n] )p;` is this typecasting possible where p is normal integer pointer `int *p` which pointing to base address of matrix

代码

#include <iostream>
void display(int, int, void* );

int main()
{
    int A[][2]= { 0, 2,
                  4, 2,
                  2, 2};
    int m=3, n=2;
    display(m, n, &A[0][0]);
}

void display(int m, int n, void *p)
{
    int (*q)[m][n]=( int(*)[m][n] )p; // This causing error

    for(int i=0; i<=m-1; i++)
    {
        for(int j=0; j<=n-1; j++)
        {
            std::cout<<q[i][j]<<" ";
        }
        std::cout<<"\n";
    }
}

输出(错误)

Cannot initialize a variable of type 'int (*)[m][n]' with
an rvalue of type 'int (*)[m][n]'

这里用户提到了这个,但它不起作用。

int (*q)[m][n]=( int(*)[m][n] )p; 所以为什么没有发生这种类型转换。

您不必对静态大小的数据使用向量,您仍然可以使用“C”样式数组。并且您可以按类型安全(和内存访问安全的方式)执行此操作,如下所示:

#include <iostream>

/*
This is an insecure way of doing things anyway since it depends on 
- typeconversion from void* (you could put anything into this function and it would try to display it)
- n and m could differ from actual sizes of the array leading to out of bounds error

void display(int m, int n, void* p)
{
    int(*q)[m][n] = (int(*)[m][n])p; // This causing error <== because it is incorrect syntax

    for (int i = 0; i <= m - 1; i++)
    {
        for (int j = 0; j <= n - 1; j++) // dont compare with <= it just not standard practice
        {
            std::cout << q[i][j] << " ";
        }
        std::cout << "\n";
    }
}
*/

// this would be the fixed size signature 
// note it is typesafe (no void*) and carries the sizes
// within the datatype
void display(int (&values)[3][2])
{
    for(int row=0; row < 3; ++row)
    {
        for(int col=0; col < 2; ++col)
        {
            std::cout << values[row][col] << " ";
        }
        std::cout << "\n";
    }
}


// to make the previous function reusable for other array sizes
// you can make it a function template
// and notice I replaced the index based for loops with range 
// based for loops for added safety 
template<std::size_t N, std::size_t M>
void display_template(int (&values)[N][M])
{
    std::cout << "\nfunction template version of display\n";

    // need a reference to a row
    // and the consts mean that display can only
    // look at the rows and values not change them
    for(const auto& row : values)
    {
        for(const auto value : row)
        {
            std::cout << value << " ";
        }
        std::cout << "\n";
    }
}


int main()
{
    // initialize 2d array in a 2d manner (nested {})
    int values[3][2] {{0,2},{4,2},{2,2}};

    display(values);
    display_template(values);

    return 0;
}