小编Yas*_*kar的帖子

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

#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)

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

c c++ malloc struct allocation

0
推荐指数
1
解决办法
327
查看次数

标签 统计

allocation ×1

c ×1

c++ ×1

malloc ×1

struct ×1