问题
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;
}
回答1:
I see in your code produce *fruit
, so, fruit
is a pointer to one or more produce objects. That means that fruit[i]
evaluates to a single actual produce
object. Since it's an object, to access its item
member, you use the .
symbol. You would only use ->
if it were a pointer. So you need to change fruit[i]->item;
to fruit[i].item
.
回答2:
Consider this simple example to make it explicit how you are accessing an object, not a pointer to an object:
int *arr = new (std::nothrow) int[10];
for(int i=0; i< 10 ; ++i)
{
arr[i]=i;
}
delete [] arr;
Each element in arr( for instance arr[0]) is a simple int, for the sake of the example it is being initialized the content of each element of the array with the index value, later the array of ints is deleted. For you case each element in the fruit array (fruit[0], fruit[1], etc...) is an object of type produce (not a pointer to an object). Therefore the access must be with the access operator . instead of ->.
来源:https://stackoverflow.com/questions/17577170/c-dynamic-memory-allocation-with-arrays-in-a-structure