C++使用数组作为多维,尽管使用指针将其作为1D进行初始化

Cra*_*y53 0 c++ arrays pointers

看起来这个代码很有效.

int main()
{
const int size = 5;
int *triangle[size], i, j;

for (i = 0; i < size; i++){
    triangle[i] = new int[i + 1];
    for (j = 0; j < i + 1; j++)
        triangle[i][j] = i + 1;
}
for (i = 0; i < size; i++){
    for (j = 0; j < i + 1; j++)
        cout << triangle[i][j];
    cout << endl;
}
for (i = 0; i < size; i++)
    delete [] triangle[i];

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

它给它输出1 22 333 4444 55555

但是不是写int*triangle[ size]一个1D数组的节目,我们没有指定关于第二个参数的任何内容.但是后来我们使用它就像一个2D数组通过写 triangle[i][j] = i + 1;我不明白j(第二个参数)来自哪里.它不应该给出编译错误或什么?

Nat*_*ica 6

int *triangle[size]是一个指针数组.在你的for循环中你做

triangle[i] = new int[i + 1]
Run Code Online (Sandbox Code Playgroud)

它将每个指针设置为指向一个数组.我们把它放在一起

triangle[i][2]
         +  +
         |  +> access the element of the array the ith pointer points to
         |
         +-> Accesses the ith pointer
Run Code Online (Sandbox Code Playgroud)