如何将值分配给指向结构的指针的固定数组
How to assign a value to a fixed array of pointers to structs
我正在尝试创建一个具有动态大小的结构数组,并尝试为每个结构分配值。 我知道我可以使用向量来轻松解决这个问题,但我这样做是为了学习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();
。
另外,您应该注意,目前它不是您的问题中所述的动态结构数组,而是指向结构的固定指针数组。
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- C++:映射结构中的结构指针
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 类的静态结构指针声明在C++
- 在两个.cpp文件之间定义全局类/结构指针
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 是否可以将无符号字符数组reinterpret_cast到仅包含C++中无符号字符成员的结构指针
- 如何在地图中使用结构指针
- 结构指针在"新"调用上给出已分配的地址?
- 铸造结构指针指向C 的工会指针
- c++ 结构指针在初始化为 NULL 时无法读取内存
- 函数中的结构指针的地址为0x1
- C 用结构指针初始化结构
- C 结构指针铸成数组Interop C#
- 方法中不允许访问结构指针
- 如何打印出结构指针
- MPI_Op_create:候选功能不可行.自定义结构指针不能解释为空指针
- 尝试将结构指针传递给类时出错
- 初始化结构指针的值
- 使用 pybind11 将自定义结构(指针向量)从 C++ 传递到 python 的方法是什么?