[英]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;
为什么? 这困扰了我好几天...
使用new
运算符分配内存时,它会执行以下两项操作:
在您的情况下( malloc
),您仅执行第一部分,因此您的结构成员未初始化。
未初始化article[0]
(即未为article[0]
调用struct product
的构造struct product
)。 因此, 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;
}
使用cin
时未初始化article [0]。 如果改用new[]
,它应该可以工作。
代替malloc-ing对象,使用new
product *article = new product[n];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.