将用户定义的二维数组传递给另一个函数

时间:2018-02-04 05:53:59

标签: arrays function multidimensional-array

我正在尝试将用户定义的二维数组从main传递给另一个函数,但是我遇到了很多错误。救命! 调用函数时发生错误。请告诉我在声明,调用和定义用户定义的函数时应该指定哪些参数。

#include<iostream>
using namespace std;
int transpose(int a[][int], int, int); //user-defined function
int main()
{
    int size;
    cout << "\nEnter the size of the matrix : "; //entering size of the 
    array
    cin >> size;
    int orignal[size][size]; //declaration of array
    cout << "\nEnter the elements in the array : "; //entering elements in 
    array
    for(int i = 0; i < size; i++)
    {
        for(int j = 0; j < size; j++)
        {
            cin >> orignal[i][j];
        }
    }
    cout << "\nThe elements in the array are :\n"; //displaying elements in 
    array
    for(int i = 0; i < size; i++)
    {
        for(int j = 0; j < size; j++)
        {
            cout << orignal[i][j] << "  ";
        }
        cout << "\n";
    }
    transpose(orignal, size, size); //calling user defined function
    return 0; 
}

int transpose(int a[][int column], int row, column)
{
    for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < column; j++)
        {
            cout << a[i][j] << "  ";
        }
        cout << "\n";
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

可以简单地完成

#include<iostream>
using namespace std;
int main()
{
int size;
cout<<"Enter size of Array :\n";
cin>>size;
int a[size][size],b[size][size];
cout<<"\nInput Matrix-A\n";
for(int i=0;i<size;++i)
{
for(j=0;pj<size;j++)
cin>>a[i][j];
cout<<endl;
}
cout<<"\nThe elements in Matrix A is :\n";
for(i=0;i<size;++i)
{
for(j=0;j<size;++j)
cout<<a[i][j];
cout<<endl;
}
for(i=0;i<size;++i)
{
for(j=0;j<size;j++)
b[i][j]=a[j][i];
}
cout<<"\nTranspose of Matrix is:\n";
for(i=0;i<size;++i)
{
for(j=0;j<size;++j)
cout<<" "<<b[i][j];
cout<<endl;
}
return 0;
}

为了将数组传递给函数, 第一种方式:

  

数组的接收参数本身可以声明为数组。

int main()
{
int age[10];
.
.
.
display(age);
return 0;
}
void display(int a[10])
{
}

第二种方式:

  

接收参数可以声明为未大小的数组。对于单个&gt;维数组,大小不是必需的,但在多维数组中,   第一维的大小不是必需的,但其他大小是必要的。

.
.
//Calling function remain same
.
.
void display(int a[])
{
........
}      

第三种方式:

  

接收参数可以声明为指针

.
.
.
void display(int *a)
{ .....}

如果您不知道大小,则始终鼓励在函数内部输入数据到多维数组。在你的情况下,只需在函数内部输入或在编码中预先定义数组的大小

最好是在全局范围内声明数组,因此主要和用户定义的函数都可以访问它。

相关问题