gpt4 book ai didi

c++ - 在运行时初始化 2D int 数组

转载 作者:行者123 更新时间:2023-11-28 04:00:27 27 4
gpt4 key购买 nike

我从一本 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 和 i 是整数,* 表示相乘。因此对于第 1 行第 2 列,t = 1,i = 2,并且 nums[1][2] = 1x4+2+1 = 7。

哦,忘了几件事。首先, () 是指定操作顺序。所以 t*4 首先完成。请注意,在这种情况下,() 是不必要的,因为乘法运算符无论如何都优先于加号运算符。

此外,我无法从您的问题中判断您是否已经知道这一点,但是 rows[t][i] 的含义是用于访问第 t 行和第 i 列的行的数组表示法。

关于c++ - 在运行时初始化 2D int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1034904/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com