J
John Carson
Steven Taylor said:I'm learning C++ from C++ Primer Plus 5th edition. I'm struggling at
the moment with declaring an array of three structures by using 'new'
to allocate memory. (this is one of the programming exercises at
the end of each chapter). My attempt is as per below. I get a
compile error indicating that -
"base operand of '->' has no pointer type 'candybar' "
// Q-09.cpp -- Question 9
#include <iostream>
struct candybar
{
//char brand[20];
std::string brand; //in this context - must use std::string
float weight;
int calories;
};
int main()
{
using namespace std;
candybar * snack = new candybar[3];
snack[0]->brand = "Mocha Munch"; // above error starts here
snack[0]->weight = 2.3;
snack[0]->calories = 350;
Replace all of the -> operators with the . operator.
snack is a pointer, but using the subscript operator dereferences the
pointer. Thus snack[0] is of type candybar, not pointer to candybar.