从函数接受二维数组(int类型)并将其返回到main函数

时间:2016-05-21 09:32:08

标签: c++ arrays function

我只想把二维数组的大小作为函数中的参数,接受数组并以某种方式将它放在main函数中以进行进一步的任务。 我试过看一些视频和帖子,但没有得到我的答案。 请一如既往地帮助我解决这个问题。

int *accept(int a,int b)
{
   int x[50][50];
 for(int i=0;i<a;++i)
 {
  cout<<"Enter elements for "<<i+1<<" th row";
   for(int j=0;j<b;++j)
   {
    cout<<"Enter "<<j+i<<" th element \n";
    cin>>x[i][j];
   }
 }
 return *x;
 }

 void main()
 {
 int arr[50][50],m,n;
 cout<<"Enter the no of rows you want : ";
 cin>>m;
 cout<<"Enter the no of columns you want : ";
 cin>>n;
 arr[50][50]=accept(m,n); //how to copy?

1 个答案:

答案 0 :(得分:0)

您可以使用memcpy()

#include <iostream>
#include <cstring>
using namespace std;

void accept(void* arr, int a, int b)
{
     int x[a][b];

     for (int i = 0; i < a; ++i)
     {
        cout << "Enter elements for " << i+1 << " th row";

        for (int j = 0; j < b; ++j)
        {
            cout << "Enter " << j+i << " th element \n";
            cin >> x[i][j];
        }
     }

     memcpy(arr, x, sizeof(int) * a * b);
 }

int main()
{
    int m, n;

    cout << "Enter the no of rows you want : ";
    cin >> m;
    cout << "Enter the no of columns you want : ";
    cin >> n;

    int arr[m][n];
    accept(&arr, m, n);

    return 0;
}