0

我正在刷新我对 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;
};

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

4

3 回答 3

0

在这里,您需要分配您的char*. 如果不是,您将有未定义的行为(通常是 a segFault

您的代码中还有两件事:

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

#include <string>

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

您可能还想使用std::vector.

于 2013-08-05T13:30:55.153 回答
0

这里的问题是您需要char* name在结构中分配内存才能存储字符。

如果您使用 C++(首选方式) ,您也可以使用string代替:char *

struct hotel {
    string name;
    short int rating, stars;
};
于 2013-08-05T13:16:43.097 回答
0

您需要包括new才能使用nothrow http://www.cplusplus.com/reference/new/nothrow/

#include <new>  //std::nothrow
于 2013-08-05T13:18:18.637 回答