使用指针将第一个(2D)数组的值复制到第二个中的函数

时间:2019-08-21 13:39:58

标签: c++

我的任务是:

  

在主函数中,定义并初始化一个二维双精度数组。定义(但不初始化)另一个尺寸与第一个相同的二维双精度数组。编写一个函数,这次使用指针将第一个数组的值复制到第二个数组中。

我尝试过:

void cpyda(double *old_array,double *new_array,int length){
    double *ptr_one=old_array;
    double *ptr_two=new_array;

    for(int i=0;i<length;i++){
        ptr_two[i]=ptr_one[i];
    }

    for(int r=0;r<2;r++){
        for(int c=0;c<3;c++){
            cout<<new_array[r][c]<<" ";
        }
        cout<<endl;
    }
}

int main(){
   double array_one[2][3]={{1,2,3},{4,5,6}};
   double array_two[2][3]={};
   cpyda(array_one,array_two, 6);
}

我一直遇到的错误是:

 function-1-4.cpp: In function 'void cpyda(double*, double*, int)':
 function-1-4.cpp:14:33: error: invalid types 'double[int]' for array 
   subscript
              cout<<new_array[r][c]<<" ";
                             ^
 main-1-4.cpp: In function 'int main()':
 main-1-4.cpp:9:11: error: cannot convert 'double (*)[3]' to 'double*'
      cpyda(array_one,array_two, 6);
       ^~~~~~~~~
 main-1-4.cpp:4:27: note:   initializing argument 1 of 'void 
 cpyda(double*, double*, int)'
 extern void cpyda(double *old_array,double *new_array,int length);

2 个答案:

答案 0 :(得分:1)

首先,在调用main()之后,我将把数组输出代码放在cpyda(...)中-毕竟,该函数仅应进行实际复制...

第二,如果您的函数应“使用指针”,则实际上使用指针,而不是声明为指针的变量,然后将其视为数组...

void cpyda(double *old_array,double *new_array,int length){
    double *ptr_one=old_array;
    double *ptr_two=new_array;

    for(int i=0; i<length; i++) {
    //    ptr_two[i]=ptr_one[i];
          *ptr_two++ = *ptr_one++
    }    
 }

int main(){
   double array_one[2][3]={{1,2,3},{4,5,6}};
   double array_two[2][3]={};
   cpyda(array_one[0], array_two[0], 6);
   for (int r=0; r<2; r++) {
        for (int c=0; c<3; c++) cout << array_two[r][c] << " ";
        cout << endl;
    }
}

您也可以通过不麻烦将指针参数复制到本地变量来使cpyda函数更加简洁……

void cpyda(double *old_array,double *new_array,int length){
    for (int i=0; i<length; i++) *new_array++ = *old_array++;
}

有帮助吗?

答案 1 :(得分:0)

这应该做

void cpyda(double** old_array, double ** new_array, int row, int column) 
{
    for (int r = 0; r < row; r++)
    {
        memcpy(&new_array[r][0], &old_array[r][0], sizeof(double) * column);
    }
    for (int r = 0; r < row; r++)
    {
        for (int c = 0; c < column; c++)
        {
            std::cout << new_array[r][c] << std::endl;
        }
    }
}

int main() {

    double** arrayOne = new double*[2];
    double** arrayTwo = new double*[2];

    for (int r = 0; r < 2; r++)
    {
        arrayOne[r] = new double[3];
        arrayTwo[r] = new double[3];
    }

    double value = 1;

    for (int r = 0; r < 2; r++)
    {
        for (int c = 0; c < 3; c++)
        {
            arrayOne[r][c] = value++;
        }
    }
    cpyda(arrayOne, arrayTwo, 2, 3);

    for (int r = 0; r < 2; r++)
    {
        delete[] arrayOne[r];
        delete[] arrayTwo[r];
    }
    delete[] arrayOne;
    delete[] arrayTwo;
}