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

Yas*_*kar 0 c c++ malloc struct allocation

#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;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么这是错误的,因为当我试图运行它时,我得到了一个分段错误.我使用GDB调试器来查看导致问题的行,这是导致此问题的行:

cin >> article[i].productName;
Run Code Online (Sandbox Code Playgroud)

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

小智 6

当您使用new运算符分配内存时,它会执行以下两项操作:

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

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