c++ - 如何在普通数组的单元格中插入结构或指针?C++
问题描述
我做了一个看起来像这样的数组,int array[array_length]; 现在我想在其中一个单元格中输入一个指针或结构(现在这些指针/结构的内容无关紧要),我该怎么做?
这是我到目前为止所做的:
const int array_length = 5;
struct Point {double _x,_y;};
void read_points(int array[array_length]);
int main(){
int array[array_length];
int i = array_length;
struct Point *temp;
while (i > 0) {
temp = new (std::nothrow) struct Point;
array[i-1] = &temp;
if (array[i-1] == NULL) {
cerr << "Cannot allocate memory\n";
exit(EXIT_FAILURE);
}
i--;
}
return EXIT_SUCCESS;
}
解决方案
在像int array[array_length];
int 这样的声明中,意味着它是一个 int 值数组。因此,您需要将其声明为Point* array[array_length];
(指向 Point 对象的指针数组)。然后您的 temp 已经是指向 Point 对象的指针,因此array[i-1] = temp;
将它们放入数组中的方法也是如此。所以你的最终代码可能如下所示:
#include <iostream>
using namespace std;
const int array_length = 5;
struct Point {double _x,_y;};
//void read_points(int array[array_length]);
int main(){
Point* array[array_length];
int i = array_length;
struct Point *temp;
while (i > 0) {
temp = new (std::nothrow) struct Point;
array[i-1] = temp;
if (array[i-1] == NULL) {
cerr << "Cannot allocate memory\n";
exit(EXIT_FAILURE);
}
i--;
}
return EXIT_SUCCESS;
}
推荐阅读
- javascript - Vuex 不对复杂对象做出反应
- php - 在 composer.json 中更新 symfony/symfony 版本
- angular - Angular 8 FormArray 的 .Net Core API ModelState 错误
- angular - 更改控件属性后,垫子微调器不会隐藏
- arrays - 如何读取对象并存储到数组中
- react-native - 反应本机位置跟踪器应用程序中的 WebSocket 与套接字 io
- c# - 使用 Azure 管理 API 列出容器组失败并出现 System.Net.Sockets.SocketException
- java - 如何对上传到服务器的 java 代码运行测试
- oracle - 如何将整列 Oracle SQL 从另一个表插入到预先存在的行中?
- reveal.js - 我们如何为每张幻灯片(而不是每个片段)创建一个 PDF 页面?