简体   繁体   中英

How to insert a structure or a pointer, inside a cell of a normal array? c++

i made an array that looks like this, int array[array_length]; now i want to enter inside one of it's cells a pointer or a struture(doesnt matter the content of these pointers/structures for now), how do i do that?

this is what i did so far:

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

In a declaration like int array[array_length];the int means that it's an array of int values. So you need to declare it as Point* array[array_length]; (array of pointers to Point objects). And then your temp is already a pointer to Point objects, so array[i-1] = temp; is the way to put them inside the array. So your final code may look like this:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM