繁体   English   中英

结构中具有数组的C ++动态内存分配

[英]C++ dynamic memory allocation with arrays in a structure

曾经有过类似的问题,但是它们都是用C而不是C ++编写的,所以我问了一个新问题。

我一直在遵循C ++教程,并在完成动态内存,指针和结构部分之后,尝试将它们放在示例程序中。

本质上,我试图拥有一个动态分配的结构数组(程序输入“ produce”:P并显示结果)。

编译器错误: 'base operand of '->' has non-pointer type 'produce'对于代码fruit[i]->item; 'base operand of '->' has non-pointer type 'produce' fruit[i]->item;

抱歉,如果代码有些冗长(我不想在出现问题的时候省去一些部分,即使这会导致问题“过于本地化”):

#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;
}

我在您的代码中看到了produce *fruit ,因此, fruit是一个或多个农产品对象的指针。 这意味着fruit[i]评估为单个实际produce对象。 由于它是一个对象,因此您可以使用访问其item成员. 符号。 仅当->指针时才使用。 因此,您需要更改fruit[i]->item; fruit[i].item

请考虑以下简单示例,以明确表明您如何访问对象,而不是指向对象的指针:

int *arr = new (std::nothrow) int[10];
for(int i=0; i< 10 ; ++i)
{
    arr[i]=i;
}
delete [] arr;

arr(例如arr [0])中的每个元素都是一个简单的int,出于示例的原因,正在使用索引值初始化该数组中每个元素的内容,然后删除int数组。 对于您而言,fruit数组中的每个元素(fruit [0],fruit [1]等)都是类型为Produce的对象(而不是指向该对象的指针)。 因此,访问必须与访问操作员一起进行 代替->

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM