c++ - 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?
解决方案
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
推荐阅读
- html - 不使用 HTML 和 CSS 的复选框显示内容(无 JS)
- ruby-on-rails - 使用 ActiveRecord 查询接口进行分组和排序
- javascript - 在 Laravel 中使用 chartjs 的问题
- asp.net - System.Data.Entity.Validation.DbEntityValidationException:'验证一个或多个实体失败
- react-native - React Native 如何绘制曲线
- java - Java 11 和 jacorb。ClassNotFoundException: javax.rmi.CORBA.Stub
- python - 适合 WCS 以治愈
- javascript - 在 2048 游戏中只向右移动一步
- angular - 使用 RxJS observables 考虑所有输入的 MIDI 设备
- excel - 查找某个标题并在其下方复制一定数量的条目