首页 > 解决方案 > C++ using arrays as multidimensional despite initalising it as 1D with pointer

问题描述

apperently this code works.

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;
}

It gives it output 1 22 333 4444 55555

But isn't writing int*triangle[ size] shows that is a 1D array, we dont specify anything about the second parameter. But then we use at it is like a 2D array by writing triangle[i][j] = i + 1;I dont understand where that j(second parameter) come from. Shouldn't it give a compile error or something?

标签: c++arrayspointers

解决方案


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

triangle[i] = new int[i + 1]

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

triangle[i][2]
         +  +
         |  +> access the element of the array the ith pointer points to
         |
         +-> Accesses the ith pointer

推荐阅读