使用 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;
为什么?这困扰了我好几天...
使用 new
运算符分配内存时,它会执行两项操作:
- 它分配内存来保存对象;
- 它调用构造函数来初始化对象。
在你的例子中(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];
相关文章:
- C++具有动态分配的字符数组的结构
- 如何为结构字段动态分配字符空间
- 结构内动态分配的数组
- 使用C++动态分配结构的多维数组
- 如何从文件读取到动态分配的指向结构的指针链表中?
- 在 c++ 中将动态分配的数组作为结构成员的分段错误?
- 在读取大型 txt 文件时动态分配结构内的向量
- C++类内部结构动态分配的方法
- 分段错误,在动态分配的结构内动态分配结构
- 动态分配一维结构数组:两种方法
- 在类存储结构中使用动态分配的数组
- 如何在C 中创建动态分配的2D结构阵列
- 动态分配的结构阵列具有动态分配的结构阵列元素
- 我在动态分配结构时遇到问题
- 使用 malloc 在C++中动态分配结构
- 如何在方法中返回数组的动态分配结构
- 动态分配结构数组很麻烦
- 动态分配结构数组:赋值问题(c++)
- 动态分配结构
- C++:使用非默认构造函数动态分配结构的成员数组