Reputation: 43
I'm having a hard time understanding why I cannot access my global 2D array in my main function after I have initialized it already in another function.
EDIT: Forgot to specify that d
is a known int variable declared before all of this, usually 3 or 4.
void init();
int **board;
int main(){
init();
cout << board[0][0];
}
void init(){
int **board = new int*[d];
for (int i = 0; i < d; i++){
board[i] = new int[d];
}
int n=d*d;
for (int i = 0; i < d; i++){
for (int j = 0; j < d; j++){
board[i][j] = n;
n--;
}
}
So the moment I try to access board[0][0]
in main()
I get an "Access violation at 0x00000000".
I enter debugging and see that board[0][0]
points to 0x000000
when being called in main()
but if I try to call it in the init()
function, at the end for example, it works perfectly and I can access any variable.
Upvotes: 0
Views: 476
Reputation: 8805
You're creating a new temporary variable:
int **board = new int*[d];
This is a memory leak and you cannot access the memory after the function. You can just do this:
board = new int*[d]; //remember to delete []!
I see you have tagged your question [c++]. If this is the case, you should be using the standard library instead of dealing with raw pointers. std::vector
and std::array
come to mind.
Upvotes: 2
Reputation: 122383
void init(){
int **board = new int*[d];
Here, you are defining a local variable board
in the function which blocks the global variable board
.
Instead, assign the value directly, don't define another variable:
void init(){
board = new int*[d];
Upvotes: 0