首页 > 解决方案 > 如何在普通数组的单元格中插入结构或指针?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;
}

标签: c++pointersstructure

解决方案


在像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;
}

推荐阅读