How to specify a dynamic 2-dimension array

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
tanbetien
New poster
Posts: 3
Joined: Fri Mar 22, 2002 2:00 am
Location: Singapore
Contact:

How to specify a dynamic 2-dimension array

Post by tanbetien » Thu Nov 28, 2002 9:07 am

Hi friend, I know how to specify a dynamic 1-dimension array. For example,
int k = 20;
char *s=new char[k];
But I don't know that for the 2-dimension array.
Anybody knows, please help me.
Thanks

tanbetien
New poster
Posts: 3
Joined: Fri Mar 22, 2002 2:00 am
Location: Singapore
Contact:

Post by tanbetien » Thu Nov 28, 2002 11:18 am

And, by the way, when I can specify the dynamic 2-dimension array, how can I call it in a function. For example, I have a 2-dimension array named S2[][], and I want to refer to it in a funtion's variable, for instance: lexico(char S2[][k], int n). Because the number k here is only known when running the program, the compiler will announce the error: unbound array (or something like that). Anyone knows the way to solve this, please help.
And, in the process of debugging, it is announced that: 0xC0000005:Access violation. Could you help me the way out of the error?
Thanks

suman
New poster
Posts: 45
Joined: Fri Oct 19, 2001 2:00 am
Contact:

Here is a way

Post by suman » Thu Nov 28, 2002 3:57 pm

Hi,
Try the following, it's copied from a help of Borland Help File.

[cpp]
#define TYPE int

TYPE **data;
int m; // THE NUMBER OF ROWS.
int n; // THE NUMBER OF COLUMNS.

try { // TEST FOR EXCEPTIONS.
data = new TYPE*[m]; // STEP 1: SET UP THE ROWS.
for (int j = 0; j < m; j++)
data[j] = new TYPE[n]; // STEP 2: SET UP THE COLUMNS
} catch (std::bad_alloc) {
// ENTER THIS BLOCK ONLY IF bad_alloc IS THROWN.
// YOU COULD REQUEST OTHER ACTIONS BEFORE TERMINATING
cout << "Could not allocate. Bye ...";
exit(-1);
}

for (int i = 0; i < m; i++)
delete[] data; // STEP 1: DELETE THE COLUMNS

delete[] data;
[/cpp]

You can pass double pointer in function. Although passing object will be much easier. Try using vector class that ships with STL. You may also try The Array Implementation posting in the algorithm section for such an implementation.

Good Luck.


- Suman

Post Reply

Return to “C++”