我正在编写一个二维数组程序,我遇到问题要打印出来,我不确定我现在正在做我的二维数组正确传递,因为它崩溃而不是运行。任何建议都会有所帮助
void initialize(int* one, int** two);
void replace(int* arr,int rows, int cols,int value);
void fill(int* arr, int rows, int cols);
void print(int** arr, int rows, int cols);
ofstream outfile;
ifstream infile;
int arrayOne[100][100];
int arrayTwo[100][100];
int main(){
int rows,cols=0;
cout << "Please input how many rows you would like in the array: ";
cin >> rows;
cout << "Please input how many columns you would like in the array: ";
cin >> cols;
fill(arrayOne[100][100],rows,cols);
//print(arrayOne[100][100],rows,cols);
system("pause");
return 0;
}
void initialize(int* one, int* two){
for(int i=0;i<100;i++){
for(int j=0;j<100;j++){
arrayOne[i][j]=0;
arrayTwo[i][j]=0;
}
}
}
void replace(int* arr,int rows,int cols,int value){
arr[rows][cols]=value;
}
void fill(int* arr, int rows, int cols){
int i=0;
for(int r=0; r < rows; r++){
for(int c=0; c < cols; c++){
replace(arr,r,c,i++);
}
}
}
void print(int** arr, int r, int c){
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
cout << arr[i][j] << " ";
}
cout << endl;
}
}
答案 0 :(得分:2)
如果您阅读了错误消息,则会明确指出您的问题。话虽如此,它并没有明确说明如何解决它。你将使用固定阵列走上一条艰难的道路......
/* arrayOne[100][100] This is an 'int' at the 101st row and 101st column.
* It isn't an address to anywhere in the array, in fact it is just beyond
* the end of your array.
*
* Regardless, even if it were a pointer, it would point to a location in memory
* that is not yours. We count starting with 0 in C/C++. So if you'd like to
* reference the 'whole' array just pass it bare:
*/
fill (arrayOne, rows, cols);
/* Of course this means that you need to fix the definition of 'fill'
* and 'replace'.
*/
void replace(int arr[100][100],int rows,int cols,int value){
arr[rows][cols]=value;
}
/* As you can see this isn't going to be friendly */
void fill(int arr[100][100], int rows, int cols){
int i=0;
for(int r=0; r < rows; r++){
for(int c=0; c < cols; c++){
replace(arr,r,c,i++);
}
}
}
您还有其他问题,但在遇到问题时可以在其他问题中提出这些问题。
答案 1 :(得分:-1)
将所有int * arr和int ** arr更改为int arr [100] []或更改为arr [] [100]。我不记得是哪一个。但是,这肯定是其中之一。