【问题标题】:Dynamic struct array terminating early动态结构数组提前终止
【发布时间】: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::stringstd::vector,因为这实际上是 C++。
  • 如果您不打算检查 NULL 的返回值,则不应使用 new (nothrow)

标签: c++ memory dynamic struct allocation


【解决方案1】:

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

您的代码中还有两件事:

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

#include <string>

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

您可能还想使用std::vector

【讨论】:

    【解决方案2】:

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

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

    struct hotel {
        string name;
        short int rating, stars;
    };
    

    【讨论】:

      【解决方案3】:

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

      #include <new>  //std::nothrow
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-16
        • 1970-01-01
        • 2020-11-09
        • 2021-10-30
        • 2020-08-23
        相关资源
        最近更新 更多