C语言返回数组的两种方法

在构造方法中,我们经常通过函数得到改变的或者新建的数组。但是使用return是无法成功返回的,如下:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
double* convertTemperature(double celsius, int* returnSize){
    double ktem,htem;
    double ans[2];
    ktem=celsius+273.15;
    htem=celsius*1.80+32.00;
    ans[0]=ktem;
    ans[1]=htem;
    return ans;
}

因为数组ans为局部变量 随着函数调用的结束,其中的各种局部变量也将被系统收回,所以无法正确返回数组值,可以采用以下方法:

方法一:使用数组指针,malloc分配动态空间。

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
double* convertTemperature(double celsius, int* returnSize){
    double* ans;
    ans=(double*)malloc(sizeof(double)*2);
    ans[0]=celsius+273.15;
    ans[1]=celsius*1.80+32.00;
    *returnSize=2;
    return ans;
}

方法二:采用static关键字

int* function(){
    static int str[5]={1,2,3,4,5};
	return str;
}

当主函数中已经定义该数组可以直接返回,如:

#include void function(int str[],int len)
{
	int i=0;
    for(i=0;i 

方法一:使用数组指针,通过指针改变数组内容

void function(int *str,int len)
{
    for(int i=0;i 

方法二:使用&引用,引用数组直接带回数组值。

#include void function(int(&str)[5],int len)
{
	int i=0;
    for(i=0;i