1

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 ?

trincot
  • 317,000
  • 35
  • 244
  • 286
Emre Kaya
  • 131
  • 5

3 Answers3

5

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);
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
3

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; 
} 
Öö Tiib
  • 10,809
  • 25
  • 44
1

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)
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
eral
  • 123
  • 1
  • 16