动态结构数组提前终止 我正在更新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; }

动态结构数组提前终止 我正在更新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; },c++,memory,dynamic,struct,allocation,C++,Memory,Dynamic,Struct,Allocation,我猜“酒店”的动态声明有问题。我哪里出错了?这里的问题是,为了存储字符,需要为结构中的char*name分配内存 您还可以使用字符串而不是 char */c> >如果使用C++(首选方式): 您需要包括new才能使用nothrow \include//std::nothrow 在这里,您需要分配您的字符*。否则,您将有一个未定义的行为(通常为segFault) 代码中还有两件事: 您应该使用而不是char*。这是C++中的一个更好的实践。(至少在这种情况下): #包括 斯特克酒店{ std::

我猜“酒店”的动态声明有问题。我哪里出错了?

这里的问题是,为了存储字符,需要为结构中的
char*name
分配内存

您还可以使用<代码>字符串而不是<代码> char */c> >如果使用C++(首选方式):


您需要包括
new
才能使用
nothrow

\include//std::nothrow

在这里,您需要分配您的
字符*
。否则,您将有一个未定义的行为(通常为
segFault

代码中还有两件事:

您应该使用而不是
char*
。这是C++中的一个更好的实践。(至少在这种情况下):

#包括
斯特克酒店{
std::字符串名;
//^^^^^^^^^^^
短整数评级,星级;
};

您可能还想使用。

您没有为
hotel::name
分配任何空间,除非您没有显示构造函数。你为什么不试试<代码>字符串>代码>?我会使用<代码> STD::String 和 STD::vector < /C> >,因为这实际上是C++。如果你不检查代码< NUL> <代码>的返回值,你不应该使用<代码>新(NoWrPoT)<代码>。
struct hotel {
    char* name;
    short int rating, stars;
};
struct hotel {
    string name;
    short int rating, stars;
};
#include <new>  //std::nothrow
#include <string>

struct hotel {
    std::string name;
  //^^^^^^^^^^^
    short int rating, stars;
};