【发布时间】:2013-08-05 13:13:54
【问题描述】:
我正在刷新我的 C++ 动态内存分配和结构的知识,突然遇到了一些麻烦。下面是部分代码,3行后停止执行,程序终止。
int n;
std::cout << "How many hotels do you want : ";
std::cin >> n;
hotel* hotels= new (nothrow) hotel[n];
for (int i= 0; i< n; i++) {
std::cout << "Hotel " << i+1 << " name : ";
std::cin >> hotels[i].name;
std::cout << "Hotel " << i+1 << " rating : ";
std::cin >> hotels[i].rating;
std::cout << "Hotel " << i+1 << " stars : ";
std::cin >> hotels[i].stars;
}
这里是“酒店”声明:
struct hotel {
char* name;
short int rating, stars;
};
我猜“酒店”的动态声明有问题。我哪里出错了?
【问题讨论】:
-
您没有为
hotel::name分配任何空间,除非您没有显示构造函数。你为什么不试试string呢? -
我会在这里使用
std::string和std::vector,因为这实际上是 C++。 -
如果您不打算检查
NULL的返回值,则不应使用new (nothrow)。
标签: c++ memory dynamic struct allocation