I'm trying to create a 2D array filled with random ints. The number of rows and columns are decided by the user. The issue is that when I run the program, the array is filled with the same number in each spot.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int** createArray(int rows, int cols){
// Create a 2D array of ints that is rows x cols
int** array = new int*[rows];
for(int i = 0;i<rows;++i){
array[i] = new int[cols];
}
// Fill the array
srand(time(NULL));
for(int r = 0; r<rows; ++r){
for(int c = 0;c<cols;++c){
array[r][c] = (rand()%100);
}
}
return array;
}
int main(int argc, char* argv[]){
int** array;
int row = atoi(argv[1]);
int col = atoi(argv[2]);
array = createArray(row,col);
for(int x=0;x<row;x++){
cout<<endl;
for (int y=0;y<col;y++){
cout<<array[row-1][col-1]<<" ";
}
}
cout<<endl;
return 0;
}
The output generally follows something along the lines of:
53 53 53
53 53 53
53 53 53
-
1[OT]: You have memleaks: you don't release array ('rows' and 'column').Jarod42– Jarod422013年12月23日 04:04:04 +00:00Commented Dec 23, 2013 at 4:04
3 Answers 3
The error is in your print loop, not your initialization.
for(int x=0;x<row;x++){
cout<<endl;
for (int y=0;y<col;y++){
cout<<array[row-1][col-1]<<" ";
}
}
That always prints the lower-right corner (row-1, col-1). You probably meant this:
for(int x=0;x<row;x++){
cout<<endl;
for (int y=0;y<col;y++){
cout<<array[x][y]<<" ";
}
}
Also a small usage tip: Don't call srand() in your createArray() function. If you call it anywhere, call it in main(), near the beginning, and make that the only place in your code it gets called.
1 Comment
Your code has several errors:
- The range in the print is wrong. It must be
array[row][col] - Don't initialize srand() every time you call the function. It's a big mistake.
- Don't use the modulo to get the random number. Multiply and divide:
100.0 * rand() / static_cast<double>(RAND_MAX) - Please! Free the memory you allocated. Call
deleteto free up the arrays you created (first free the internal arrays and finally the main array)
Comments
In your main row and cols arn't changing they are just the dimensions of your array.
You have to print the values based on the corrdinates:
for(int x=0;x<row;x++){
cout<<endl;
for (int y=0;y<col;y++){
cout<<array[x][y]<<" ";
}
}
cout<<endl;
If you want to print the arry reversly you have to do this
for(int x=0;x<row;x++){
cout<<endl;
for (int y=0;y<col;y++){
cout<<array[row-1-x][row-1-y]<<" "; // not row-1 and cols-1 as they're not changing
}
}
cout<<endl;
Comments
Explore related questions
See similar questions with these tags.