Magos is correct, and this is something that I see too often. The main reason you don't want to do this is when mulitple files use the header with the pointer. What you should do is this.
Code:
//inside header
extern int **ptr;
//inside ONE of your files
int **ptr;
//in one of your files
void dynamicArray(int num_rows, int num_cols)
{
p = new int*[num_rows];
for (int i = 0 ; i < num_rows; i++ )
p[i] = new int[num_cols];
}
Okay, there are a couple of ways to make sure that memory is allocated.
Code:
void dynamicArray(int num_rows, int num_cols)
{
using namespace std;
try {
p = new int*[num_rows];
} catch(bad_alloc e) {
cerr << e.what();
return;
}
for (int i = 0 ; i < num_rows; i++ ) {
try {
p[i] = new int[num_cols];
} catch(bad_alloc e) {
cerr << e.what();
return;
}
}
}
//alternatively
void dynamicArray(int num_rows, int num_cols)
{
using namespace std;
p = new int*[num_rows];
if(!p) {
cerr << "not enough memory" << endl;
return;
}
for (int i = 0 ; i < num_rows; i++ ) {
p[i] = new int[num_cols];
if(!p) {
cerr << "not enough memory" << endl;
return;
}
}
}