IM YouTube上观看https://www.youtube.com/watch?v=8XAQzcJvOHk动态分配阵列本教程根据在C++用户输入动态分配阵列根据在C++用户输入
这是他的代码
1 int main()
2 {
3 int *pointer = nullptr;
4
5 cout << "how many items u are gonna enter" << endl;
6 int input;
7 cin >> input;
8
9 pointer = new int[input];
10
11 int temp;
12
13 for (int counter = 0; counter < input; counter++) {
14 cout << "enter the item " << counter + 1 << endl;
15 cin >> temp;
16 *(pointer + counter) = temp;
17 }
18
19 cout << "the items you have entered are" << endl;
20 for (int counter = 0; counter < input; counter++) {
21 cout << counter + 1 << " item is " << *(pointer + counter) << endl;
22 }
23
24 delete[]pointer;
25
26 return 0;
27}
IM停留在第16行,我不明白为什么是,内部的(),指针变量和计数器被添加到彼此
'*(指针+计数器)'是另一种(也更奇怪)的方式来写'指针[计数器]'。目前还不清楚为什么作者选择以这种方式混淆事件。无论如何,使用'std :: vector'代替原始指针和手动内存管理会更好。 –
在实际的代码中,这应该是'std :: vector'。 –
虽然我给出了主动编码建议:在使用它之前不要定义“指针”,即int * pointer = new int [input];';并在'for'循环体内定义'temp',因为这是它唯一使用的地方。 –