Multi-Dimensional Array Indexing

Hi there

Need a little help here

I have simple multi-dimensional array where you enter the amoun columns and rows in the array and all the values of the array are assigned '0'. I dont have much knowledge of multi-dimensional arrays and i have two problems.

1. When i enter larger column/rows numbers ike 30 the program crashes and
2. I need to assign an index for the rows and colums like say

1 2 3 4
0 0 0 0 A
0 0 0 0 B

Is there anyway i could get this done?

Heres le program

------------------------------------------------------------
int RowNum, ColumnNum;


printf("Please enter how many rows you would like in the array\n");
scanf("%d", &RowNum);
printf("\nPlease enter how many columns you would like in the array\n");
scanf("%d", &ColumnNum);

int num[RowNum-1][ColumnNum-1];

int counter1, counter2;

for(counter1 = 0; counter1 <= RowNum - 1; counter1++)
{
for(counter2 = 0; counter2 <= ColumnNum - 1; counter2++)
{
num[counter1][counter2] = 0;
}
}
printf("Displaying the result of the array being filled with 0's\n");
for(counter1 = 0; counter1 <= RowNum - 1; counter1++)
{
for(counter2 = 0; counter2 <= ColumnNum - 1; counter2++)
{
printf("%d, ",num[counter1][counter2]);
}
printf("\n");
}
getch();
return 0;
-------------------------------------

THANKS FOR THE HELP!
Last edited on
*Disch stabs multidimentional arrays with a rusty knife*

A few things stand out:

 
int num[RowNum-1][ColumnNum-1];


- You can't do this. Is this even compiling? It shouldn't be. You can't use non-const variables in array definitions like this. If the array is to be dynamically sized, you need to create it with new.

- Why -1?

Dynamically allocating a 2D array is a big pain in the butt. You're better off just making a 1D array:

1
2
3
4
5
6
7
8
int* num = new int[RowNum * ColNum];

// to get a thing at X,Y ... instead of doing num[X][Y] or something similar, you can do this:

num[ (Y*RowNum) + X ];

// .. and then don't forget to clean up:
delete[] num;


Or if you want to forgo the cleanup requirement, you can just use a vector:

1
2
3
4
5
6
7
vector<int> num( RowNum * ColNum, 0 );  // make your 2D array
//  note the above line also zero's the array, so you don't have to loop and set everything to zero

// access same as before:
num[ (Y*RowNum) + X ];

// no need to cleanup -- vector takes care of it for you 


If you REALLY want 2D arrays (ugh ugh ugh) you can do it, but ugh. I'll leave it to someone else to show examples. I'd rather not have any part in steering you down that path.
Disch wrote:
*Disch stabs multidimentional arrays with a rusty knife*


Can't have that! *hands Disch a vorpal dagger for next time*
Topic archived. No new replies allowed.