CodeX
CodeX

Reputation: 17

Declaring and initializing a global 2D array

//gives the error expecting a declaration

 int** my_array; 
 for (int i=0; i<200; i++)
 {
     my_array[i]= new int [200];
 }

//initialize array with zeroes
 for (int i = 0; i<200; i++)
 {
     for (int j = 0; j<200; j++)
     {
        my_array[i][j] =0;
     }
 }

In brief:

The 2D array is declared globally

It is initialized in the main. The main calls a function that saves 0's or 1's in specific cells of the array

The array is then printed by the main

Also advice whether the flow is correct?

Upvotes: 0

Views: 5219

Answers (2)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

If you want an array of an array of 200 bools, you could use std::array and std::bitset.

#include <bitset>
#include <array>
//...
std::array<200, std::bitset<200>> my_array;

Second, your code, even if you fix the syntax error is wrong. You would need to create my_array this way:

int** my_array;
//...
my_array = new int * [200];
for (int i = 0; i < 200; ++i )
   my_array[i] = new int [200];

Then somewhere you have to delete this memory:

for (int i = 0; i < 200; ++i )
   delete [] my_array[i];
delete [] my_array;

An alternate that creates a contiguous block and uses only two calls to new[]:

my_array = new int * [200];
int *pool = new int [200*200];
for (int i = 0; i < 200; ++i, pool += 200 )
   my_array[i] = pool;

Then somewhere you have to delete this memory:

delete [] my_array[0];
delete [] my_array;

However I advise you use a container such as the std::array, std::bitset, std::vector, etc. instead of the int** approach.

Upvotes: 1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145269

Regarding your syntax error, it's probably due to something before the code you have shown.

The shown code,

 int** my_array; 
 for (int i=0; i<200; i++)
 {
     my_array[i]= new int [200];
 }

//initialize array with zeroes
 for (int i = 0; i<200; i++)
 {
     for (int j = 0; j<200; j++)
     {
        my_array[i][j] =0;
     }
 }

compiles fine as the body of a function.


Regarding the logic, which is incorrect and which uses troublesome constructs, do this:

 auto my_array = vector<vector<bool>>( 200, vector<bool>( 200 ) );

where vector is std::vector from the <vector> header.

This avoids the raw pointers, the new-ing`, the loops, etc., all that you find problematic.


Alternatively you can declare it like this:

 vector<vector<bool>> my_array( 200, vector<bool>( 200 ) );

Note that a global variable is usually troublesome, best avoided.

Upvotes: 1

Related Questions