作为c ++的新手,我一直在练习问题.我写的一个程序包括结构和数组的使用:
#include <iostream>
using namespace std;
int main (void){
struct CandyBar{
char brandName[200];
float weight;
int calories;
};
CandyBar snacks[3] = {
{"Cadbury's Flake",23.5,49},
{"Cadbury's Wispa",49.3,29},
{"Cadbury's Picnic",57.8,49},
};
for(int i=0;i<3;i++){
cout << "Brand Name: " << snacks[i].brandName << endl;
cout << "Weight: " << snacks[i].weight << endl;
cout << "Calories: " << snacks[i].calories << endl;
snacks++;
}
cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上述程序失败了,因为"零食++",但我不明白为什么.据我了解数组,它们由指针("零食")和对象([])两部分组成,所以当我增加指针时,"snack ++"不应该工作吗?
谢谢丹
只需删除snacks++;
你已经使用变量i作为数组中的索引.
如果你想使用指针算术:
a.你应该定义一个指向数组开头的指针并使用它而不是使用数组.
湾 i在访问数据时,您应该使用指针而不是带索引的数组.
struct CandyBar* ptr = snacks;
for(int i=0;i<3;i++){
cout << "Brand Name: " << ptr->brandName << endl;
cout << "Weight: " << ptr->weight << endl;
cout << "Calories: " << ptr->calories << endl;
ptr++;
}
Run Code Online (Sandbox Code Playgroud)