如何将值分配给指向结构的指针的固定数组

How to assign a value to a fixed array of pointers to structs

本文关键字:结构 指针 数组 分配      更新时间:2023-10-16

我正在尝试创建一个具有动态大小的结构数组,并尝试为每个结构分配值。 我知道我可以使用向量来轻松解决这个问题,但我这样做是为了学习C++的基础以及它的核心是如何工作的。

本例中的结构为

struct car
{
        std::string make;
        int year;
};

然后在main()函数中,我有:

car* cars[catSize];
for (int i = 0; i < catSize; ++i)
{
     cars[i] = new car
     cout << "Enter the make for car " << i << ": ";
     char ch;
     string tempMake = "";
     cin.get(ch);
     while(ch != 'n')
     {
           tempMake += ch;
           cin.get(ch);
     }
     cars[i]->make = tempMake;
     cout << "Enter the year of car # " << i << ": ";
     cin >> cars[i]->year;
}

运行上述操作会在输入 make 并按 Enter 后立即给我一个分段错误。 有人可以帮助解释发生了什么吗?

似乎在您

输入数组大小后,'n'会保留在输入缓冲区中并干扰进一步的输入。

此外,您应该将catSize作为常量,因为并非所有编译器都支持VLAs

如果您仍然想使用 VLA,则应在读取数组大小后添加cin.ignore();

另外,您应该注意,目前它不是您的问题中所述的动态结构数组,而是指向结构的固定指针数组