Being new to c++ I’ve been practicing with questions. One program I wrote includes the use of structs and arrays:
#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;
}
The above program fails becuase of the “snacks++”, but I can’t understand why. As I understand arrays they are made of two parts the pointer (“snacks”) and the object ([]), so shouldn’t the “snacks++” work as I am incrementing the pointer?
Thanks
Dan
just remove the
snacks++;you are already using the variable
ias a index in the array.if you do want to use a pointer arithmetics:
a. you should define a pointer to the start of the array and work with it rather then work with the array.
b. you should use a pointer instead of the array with index
iwhen accessing the data.