简体   繁体   中英

How to declare a global 2d 3d 4d … array (heap version) variable that could be used in the entire program?

class1.cpp

int a=10; int b=5; int c=2;
//for this array[a][b][c]

int*** array=new int**[a];


for(int i =0; i<a; i++)
{ 
    array[i] = new int*[b];        
    for(int k =0; k<b; k++) 
    {
       array[i][k] = new int[c];
    }  
}

how can i use this array in other .cpp files ?

Instead of manually allocating an array you should at least use a std::vector . What you would do is have a header file that contains

extern std::vector<std::vector<std::vector<int>>> data;

that you will include in all the cpp files you wish to share the vector with and then in a single cpp file have

std::vector<std::vector<std::vector<int>>> data = std::vector<std::vector<std::vector<int>(a, std::vector<std::vector<int>>(b, std::vector<int>(c)));

and now you will have a global object that is shared and it has a managed lifetime.


You shouldn't really use a nested vector though. It can scatter the data in memory so it isn't very cache friendly. You should use a class with a single dimension vector and pretend that it has multiple dimensions using math. A very basic example of that would look like

class matrix
{
    std::vector<int> data;
    int row; // this really isn't needed as data.size() will give you rows
    int col;
    int depth;
public:
    matrix(int x, int y, int z) : data(x * y * z), row(x), col(y), depth(z) {}
    int& operator()(int x, int y, int z) { return data[x + (y * col) + (z * col * depth)]; }
};

and then the header file would be

extern matrix data;

and a single cpp file would contain

matrix data(a, b, c);

Prefer std::array or std::vector to raw arrays. You had constant dimensions so use std::array . Declare it in header file:

// header.h
#pragma once  // or use multiple inclusion guards with preprocessor
#include <array>

const int a = 10;
const int b = 5;
const int c = 2;

using Array3D = std::array<std::array<std::array<int,c>,b>,a>;

extern Array3D array3d;  // extern indicates it is global

Define it in cpp file:

// class1.cpp
#include "header.h"

Array3D array3d;

Then include the header wherever you want to use it.

// main.cpp
#include "header.h"

int main()
{
    array3d[3][2][1] = 42; 
} 

I am not sure I have understood what exactly you mean but simply :

class1 obj1;
obj1.array[i][j][k] // assuming you make the array public and already initialized in the constructor(and dont forget to delete it in the destructor)

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