首页 > 解决方案 > 混淆从“int []数组”到“指向int的指针”的显式衰减?

问题描述

我是一个正在随机学习 C++ 的新手。

在接下来的前三个案例中,我可以消化正在发生的事情,因为隐含衰减的模式很清楚。

“一个”数组X被隐式衰减为“指向”的指针X

void case1()
{
    int a[] = { 1,2,3,4,5,6 };
    int *b = a;// array of int ---> pointer to int
}

void case2()
{
    int input[][3] = { {1,2,3},{4,5,6} };
    int(*output)[3] = input;// array of int[] ---> a pointer to int[]

    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 3; j++)
            cout << output[i][j] << endl;
}

int case3()
{
    int input[][3] = { {1,2,3},{4,5,6} };

    int* aux[2];

    aux[0] = input[0];// array of int ---> pointer to int
    aux[1] = input[1];// array of int ---> pointer to int

    int** output = aux;// array of int* ---> pointer to int*

    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 3; j++)
            cout << output[i][j] << endl;
}

问题

但是,我真的对以下第四种情况感到困惑。

int case4()
{
    int input[][3] = { {1,2,3},{4,5,6} };

    int* aux[2];
    aux[0] = (int*)input;// array of int[] ---> pointer to int
    aux[1] = aux[0] + 3;

    int** output = aux;// array of int* ---> pointer to int*

    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 3; j++)
            cout << output[i][j] << endl;
}

“一个数组int[]”如何可以显式衰减为“指向”的指针int

aux[0] = (int*)input;// array of int[] ---> pointer to int

欢迎任何简单的解释!

标签: c++

解决方案


“一个int []数组”如何可以显式衰减为“指向int的指针”?

学究术语:“显式衰减”是矛盾的。根据定义,衰减是一种隐式转换。

回答“如何将 [array] 明确地 [converted] 为 [a pointer that is not type of the first element]?”

这是因为数组可以衰减为指针,并且所有数据指针都可以显式转换(重新解释)为任何其他数据指针类型。在这种情况下,input衰减为 a int(*)[3]然后显式转换为int*

尽管它的格式肯定很好,但另一个问题是通过显式重新解释的指针间接是否具有定义的行为。重新解释指针的规则是复杂而微妙的——假设它保证按照你观察到的方式运行是很不安全的。我会更有信心写作:

aux[0] = *input;

在这里,input数组衰减为指向第一个子数组的指针,该指针被间接获取左值,然后衰减为指向子数组元素的指针。


更一般地说,在使用显式转换(T)expr或函数转换T(expr)或重新解释 cast时要非常小心reinterpret_cast<T>(expr)。除非您可以引用使它们的使用得到明确定义的标准规则,否则不要使用它们。


推荐阅读