Trying to create a 2D array
im trying to create a 2D array using a random generator but the compiler keeps giving me compiling error no matter how i modify the calling function
#include <iostream>
#include <ctime>
using namespace std;
const int MAX = 4;
void constructArray (int a [][MAX], int);
int main()
{
int a [MAX];
srand (time (NULL));
constructArray (a [][MAX], MAX);
}
void constructArray (int a [][], int size)
{
for (int i = 0; i < size; i++)
a [i][size] = rand () % 10;
}
number87
Junior Poster in Training
83 posts since Jan 2008
Reputation Points: 10
Solved Threads: 0
And array cannot contain 2 empty dimensions in a function. You must fill in at least the left dimension.
WaltP
Posting Sage w/ dash of thyme
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
oh i used a function coz the array would be part of a larger program....
so...if i wanna print the array on screen now...i added in a few more lines....but the compiler gives me an error msg at line 21....
whats wrong there? i filled up both dimensions of the array, why cant it work?
#include <iostream>
using namespace std;
const int MAXROW = 4;
const int MAXCOL = 10;
int main()
{
srand(time(NULL));
int a [MAXROW][MAXCOL];
for (int row = 0; row < MAXROW; row++)
{
for (int col = 0; col < MAXCOL; col++)
{
a[row][col] = rand () % 10;
}
cout << a[row][col] << "\t";
cout << endl;
}
}
number87
Junior Poster in Training
83 posts since Jan 2008
Reputation Points: 10
Solved Threads: 0
gives me an error msg at line 21....
You've declared 'col' inside the inner for loop. That means that when the loop is done, col is outside of scope.
To solve this problem you would have declare 'int col' in the same scope as where you use it. So right after this line : int a [MAXROW][MAXCOL]; for example. Just put a int col = 0; after it, and remove the 'int' delcaration from the for loop
:
#include <iostream>
#include <time.h>
using namespace std;
const int MAXROW = 4;
const int MAXCOL = 10;
int main()
{
srand(time(NULL));
int a [MAXROW][MAXCOL];
int col=0 ,row =0;
for (row = 0; row < MAXROW; row++)
{
for (col = 0; col < MAXCOL; col++)
{
a[row][col] = rand () % 10;
}
cout << a[row][col] << "\t";
cout << endl;
}
return 0;
}
Please note the return 0; at the end of the program.
I didn't check your logic, so the program may not give you the correct output.
Nick Evan
Not a Llama
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
If you want to display the entire 'matrix' you might want to move line 23: cout << a[row][col] << "\t"; inside thee 'for'loop. (on line 21)
Nick Evan
Not a Llama
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403