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

Dynamically allocating a structure in C++ using malloc

本文关键字:动态分配 结构 C++ malloc 使用      更新时间:2023-10-16
#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;

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

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

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

在你的例子中(malloc(,你只做第一部分,所以你的结构成员是未初始化的。

article[0]没有

初始化(即struct product的构造函数没有被调用article[0](。因此,article[0].productName也没有初始化。

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

尝试使用这个:

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

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

不要错误定位对象,而是使用 new

product *article = new product[n];