C++传入数组给函数和从函数返回数组

C++传入数组给函数和从函数返回数组

作者:Luyu

C++中函数是不能直接返回一个数组的,但是数组其实就是指针,所以可以让函数返回指针来实现。指针存放着数组的首地址,指针这个变量就是存地址的容器。

以下博文对我有所帮助,对作者表示感谢。
怎样让函数返回数组 - 博客园
怎样让函数返回数组 - CSDN
以上链接只讲述了如何从函数A返回数组arr[]至main(),但是没有讲如何将main()中的返回的数组arr[]再次传入另一个函数B。

1 目的

C++中经常遇到数组在函数之间的传递问题。
为了实现从主函数main()调用函数A和函数B,其中,函数A返回数组,返回值为数组的首地址(指针x),将其返回至main(),然后再将此数组以指针方式传入函数B,调用关系如下:
main() ------> 调用函数A ------> 返回数组arr[] ------> 传入函数B ------> 在函数B中读取arr[]

2 代码

主函数main.cpp

#include 
#include 

#include "coords_cen.h"
#include "display.h"

using namespace std;

int main ()
{
    // parameter of the physical problem
    double L = 1.0;
    double N = 20.0;
    double Dx = L/N;
    // define a pointer
    double* p1 ;
    // function coords_cen.cpp, return value of the function point to a pointer
    p1 = coords_cen(Dx,N,L);
    // function display.cpp, 
    // transfer the p1 (pointer/firstaddress of the array)
    display(Dx,N,L,p1);


    return 0;
}

函数coords_cen.cpp

/*  the return value of this function
is a pointer, which point to the first
address of the return value (array)  */

/* where the array x[] was generated by
the dynamic array*/

#include 
#include "coords_cen.h"
using namespace std;

double* coords_cen(double Dx,double N,double L)
{
    const int n=N;
    // static double x[n]; // another option
    double* x = new double[n]; // dynamic array

    for (int i=0; i<=(n-1); i++)
    {
        x[i] = (Dx/2)*(2*i+1);
    }

    return x;
    delete []x;
}

由于C++规定不允许返回一个未知长度的数组,因此无法使用以下方式在函数中定义数组:

	double x[n]; 

必须采取static限定:

	static double x[20]; // n=20

但是实际编程中不可能指定n的大小,因此解决的关键就是动态数组:

    double* x = new double[n]; // dynamic array

这就解决了数组返回值的问题,实际上返回的是数组的首地址/指针/数组名。
使用完毕后将其删除:

    delete []x;

函数display.cpp

// location of element's centers and interfaces
#include 
#include "display.h"
using namespace std;

void display(double Dx,
             double N,
             double L,
             double* coords_cen)
{

    cout<<"Dx: "<<Dx  <<endl;
    cout<<"N:  "<<N  <<endl;
    cout<<"L:  "<<L <<endl;

    for (int i=0; i<=(N-1); i++)
    {
        cout<<"coords_cen["<<i<<"]: "<<*(coords_cen+i)<<endl ;
    }
}

头文件coords_cen.h

#ifndef COORDS_H_INCLUDED
#define COORDS_H_INCLUDED

double* coords_cen(double Dx,double N,double L);

#endif // COORDS_H_INCLUDED

头文件dispaly.h

#ifndef DISPLAYVAR_H_INCLUDED
#define DISPLAYVAR_H_INCLUDED

void display(double Dx,
             double N,
             double L,
             double* coords_cen);

#endif // DISPLAYVAR_H_INCLUDED

你可能感兴趣的:(编程杂记,C++,数组,函数,指针)