There have been similar questions to this but they are all in C, rather than C++, so I have asked a new question.
I have been following a C++ tutorial and after completing the dynamic memory, pointers and structure sections I tried to put them together in an example program.
Essentially, I am trying to have a dynamically allocated array of a structure (the program inputs "produce" :P and displays the result).
The compiler errors: 'base operand of '->' has non-pointer type 'produce' for the code fruit[i]->item;
Sorry if the code is a bit long winded (I didn't want to leave out sections in case they were the problem, even if this results in the question being 'too localised'):
#include <iostream> #include <string> #include <new> using namespace std; struct produce { int price; string item; }; int main(void) { int num; int i; //Get int for size of array cout << "Enter the number of fruit to input: "; cin >> num; cout << endl; //Create a dynamically allocated array (size num) from the produce structure produce *fruit = new (nothrow) produce[num]; if (fruit == 0) { cout << "Error assigning memory."; } else { //For 'num', input items for (i = 0; i < num; i++) { cout << "Enter produce name: "; //Compiler error: 'base operand of '->' has non-pointer type 'produce' cin >> fruit[i]->item; cout << endl; cout << "Enter produce price: "; cin >> fruit[i]->price; cout << endl; cout << endl; } //Display result for (i = 0; i < num; i++) { cout << "Item: " << fruit[i]->item << endl; cout << "Cost: " << fruit[i]->price << endl; cout << endl; } //Delete fruit to free memory delete[] fruit; } return 0; }
cin >> fruit[i].item;fruit[i]returns the reference to an object ,not a pointer to an object. So you have to use the dot operator, not the arrow operator.fruit[i]is an instance ofproduce, it's not a pointer toproduce. Using->on it is thus wrong as the compiler already indicated.fruitis a pointer. Butfruit[i]is an object.