使用 malloc 在 C++ 中动态分配结构

Dynamically allocating a structure in C++ using malloc

#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct product{
        string productName;
        float price;
};

int main()
{
    struct product *article;
    int n=2; // n represent here the number of products
    article= (product*) malloc(n * sizeof(product));
    for(int i=0;i<n;i++)
    {
        cin >> article[i].productName; // <=> (article+i)->productName;
        cin >> article[i].price;
    }

    for(int i=0;i<n;i++)
    {
        cout << article[i].productName <<"\t" << article[i].price << "\n";
    }
    return 0;
}

我的问题是为什么这是错误的,因为当我尝试 运行 时我遇到了分段错误。我使用 GDB 调试器查看是哪一行导致了问题,这是导致此问题的那一行:

cin >> article[i].productName;

为什么?这困扰了我几天...

article[0] 未初始化(即 struct product 的构造函数尚未为 article[0] 调用)。所以article[0].productName也没有初始化

使用 new product[n] 而不是 (product*) malloc(n * sizeof(product)) 来初始化数组元素(并通过传递性元素的成员)。

而不是 malloc-ing 对象,使用 new

product *article = new product[n];

当您使用 new 运算符分配内存时,它会做两件事:

  1. 它分配内存来保存一个对象;
  2. 它调用构造函数来初始化对象。

在您的情况下 (malloc),您只执行了第一部分,因此您的结构成员未初始化。

试试这个:

#include <iostream>
#include <string>
using namespace std;
struct product{
    string productName;
    float price;
};

int main()
{
    int n = 2; // n represent here the number of products
    product *article = new product[n];
    for (int i = 0; i<n; i++)
    {
        cin >> article[i].productName; // <=> (article+i)->productName;
        cin >> article[i].price;
    }

    for (int i = 0; i<n; i++)
    {
        cout << article[i].productName << "\t" << article[i].price << "\n";
    }
    return 0;
}

article[0] 在您使用 cin 时未初始化。如果您改用 new[],它应该可以工作。