[英]Passing 2D array to function
我有個問題。 我正在創建一個矩陣計算器。 我想要的是選擇矩陣的大小。 我有兩個二維數組(a)和(b),我用整數填充數組。 問題是整數(我保存在數組中的常數)沒有出現,只是它們所在的位置。 只是指針似乎沒有取消引用。 不知道怎么了。
void rotater(int* a,int* b,int select)
{
int* matrix;
if(select == 1)
{
for(int d = 0; d < i; d++)
{
for(int c = 0; c < j; c++)
{
cout << *(a+c) << *(a+d) << " ";
//if i choose the size as 2x2 this comes out as a
//matrix {11,12;21,22} just as positions not my
//numbers that i choose
}
cout << endl;
}
}
else if(select == 2)
{
for(int d = 0; d < y; d++)
{
for(int c = 0; c < x; c++)
{
cout << *(b+d) <<*(b+c) <<" ";
}
cout << endl;
}
}
}
int a[i][j];
int b[x][y];
int *matrix1 = &a[0][0];
int *matrix2 = &b[0][0];
cout << endl;
cout << "Choose_matrix: " << "(1,2,both)" << endl;
cin >> matrix;
f = matrix //I have function that changes char matrix to int f
cout << endl;
cout << "Choose_operand: " << "(rotr,rotl,+,-,*,/,diag)" << endl;
cin >> operand;
e = operand // I have function that changes char operand to int e
switch(e)
{
case 1:
rotater(matrix1, matrix2, f); // calling function with 3 parameters
break;
default:
return 0;
}
首先,您正在使用C ++,因此應盡可能避免使用C樣式數組和原始指針。 我建議使用std::vector<int>
,或者因為您想要一個恆定的大小,所以建議std::array<int>
。
我不明白為什么要在rotater
函數中包含兩個數組。 每個參數都有相同的邏輯,那里有很多冗余代碼。
您在rotater
中的參數要求輸入一個int*
,但是當您調用該函數時,會給它一個int[][]
,它是另一種數據類型。
話雖這么說,您的代碼中有很多東西沒有明確的功能。 最重要的是,您沒有包含main()
函數,因此我無法編譯您的代碼。 如果是我,我將通過調試器運行您的程序,以了解發生了什么事。 我相信這就是您要追求的目標。
#include <iostream>
void matrix_display(int *mat, const int x_size, const int y_size)
{
for ( int x = 0; x < x_size; x++ )
{
for ( int y = 0; y < y_size; y++ )
{
std::cout << *(mat + x) << *(mat + y) << " ";
}
}
std::cout << std::endl;
}
int main()
{
const int X_SIZE = 2;
const int Y_SIZE = 2;
int matrix[X_SIZE*Y_SIZE] = {4, 7, 3, 7};
matrix_display(matrix, X_SIZE, Y_SIZE);
return 0;
}
再次,如果是我,我將使用std::array<std::array<int, 2>, 2>
而不是int*
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.