【发布时间】:2009-06-23 20:15:40
【问题描述】:
我从一本 C++ 书籍中获得了以下代码,但我无法弄清楚初始化是如何工作的。
据我所知,有一个外部 for 循环通过行循环,而内部循环 骑自行车穿过柱子。但这是我不明白的将值分配到数组中。
#include <iostream>
using namespace std;
int main()
{
int t,i, nums[3][4];
for(t=0; t < 3; ++t) {
for(i=0; i < 4; ++i) {
nums[t][i] = (t*4)+i+1; //I don't understand this part/line
cout << nums[t][i] << ' ';
}
cout << '\n';
}
return 0;
}
所以这里有一些问题。
- 我无法理解 2D int 数组
nums[3][4]的初始化。是什么分隔了(t*4)+i+1,以便编译器知道在哪里分配什么? - 如何根据已分配的值知道哪些值将存储在行和列中?
- 为什么会有星号?
-
t*4周围的括号是什么意思?
我了解初始化二维数组如下例所示。
#include <iostream>
using namespace std;
int main() {
char str[3][20] = {{"white" "rabbit"}, {"force"}, {"toad"}}; //initialize 2D character array
cout << str[0][0] << endl; //first letter of white
cout << str[0][5] << endl; //first letter of rabbit
cout << str[1][0] << endl; //first letter of force
cout << str[2][0] << endl; //first letter of toad
return 0;
}
据我所知,在记忆中是这样的。
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 w h i t e r a b b i t 0
1 f o r c e 0
2 t o a d 0
谢谢。
【问题讨论】:
-
(t*4)+i+1 没有魔法;它只是意味着 (t 乘以 4 ) 加 i 加 1。如果 t 为 0 而 i 为 0,则得到 0*4 + 0 + 1 = 1;如果 t 是 1 并且 i 是 1 ,你会得到 1*4+1+1 = 6 等等。
标签: c++ arrays initialization declaration multidimensional-array