无法从int [] []转换为int*

cam*_*cam 1 c++ arrays pointers

我有一个3x3数组,我正在尝试创建一个指针,我不断得到这个数组,是什么给出的?

我如何定义指针?我已经尝试了[]和*的每个组合.

是否有可能做到这一点?

int tempSec[3][3];

int* pTemp = tempSec;
Run Code Online (Sandbox Code Playgroud)

Ste*_*sop 15

你可以做 int *pTemp = &tempSec[0][0];

如果要将3x3数组视为int*,则应该将其声明为a int[9],并使用tempSec[3*x+y]而不是tempSec[x][y].

或者,也许你想要的是int (*pTemp)[3] = tempSec什么?那将是指向tempSec的第一个元素的指针,第一个元素本身就是一个数组.

实际上,您可以使用指向2D数组的指针:

int (*pTemp)[3][3] = &tempSex;
Run Code Online (Sandbox Code Playgroud)

然后你会像这样使用它:

(*pTemp)[1][2] = 12;
Run Code Online (Sandbox Code Playgroud)

这几乎肯定不是你想要的,但在你的评论中,你确实要求它......

  • 是的,但它不会有类型`int*`.我不知道你的问题的哪些部分是你想要的部分,哪些不是你... (3认同)
  • @DoctorT.不,"int**"不是指向2D数组的真正指针.它是一个指向`int*`的指针.我在评论中提到的怪异特别是指向3x3 int数组的指针.同样,`int*`不是指向1D数组的真实指针,它是指向特定元素的指针(如果是通过数组名称衰减获得的话,则为第一个).C和C++中的数组具有作为其类型的一部分的大小,因此指向它们的"真实"指针也具有大小. (2认同)

Mar*_*ork 6

它更容易使用typedef

typedef int  ThreeArray[3];
typedef int  ThreeByThree[3][3];

int main(int argc, char* argv[])
{
    int         data[3][3];

    ThreeArray* dPoint    = data;
    dPoint[0][2]          = 5;
    dPoint[2][1]          = 6;   

    // Doing it without the typedef makes the syntax very hard to read.
    //
    int(*xxPointer)[3]    = data;
    xxPointer[0][1]       = 7;

    // Building a pointer to a three by Three array directly.
    //
    ThreeByThree*  p1     = &data;
    (*p1)[1][2]           = 10;

    // Building a pointer to a three by Three array directly (without typedef)
    //
    int(*p2)[3][3]        = &data;
    (*p2)[1][2]           = 11;

    // Building a reference to a 3 by 3 array.
    //
    ThreeByThree&  ref1   = data;
    ref1[0][0]            = 8;

    // Building a reference to a 3 by 3 array (Without the typedef)
    //
    int(&ref2)[3][3]      = data;
    ref2[1][1]            = 9;


    return 0;
}
Run Code Online (Sandbox Code Playgroud)