向函数传递矩阵和从函数返回矩阵

时间:2016-07-23 04:20:51

标签: c++ arrays

我正在编写一个将1D数组发送到函数的c ++程序。该函数操纵数组并返回另一个相同顺序的数组。 代码如下。我在编译时遇到问题。请帮我解决错误。 谢谢#include

#include <ctime>
#include<cstdlib>
using namespace std;
long double * gradiv(long double *,int,long double);

int main ()
{
    int NN=3,c;
    long double *pp;
    long double hx;
    long double matt[NN+2]={10,9,30,63,50};
    pp = gradiv(matt,NN,1.0);
    for (c=0;c<NN+1;c++)
        cout<<endl<< *(pp+c)<<endl;
    return 0;
}


long double *gradiv(long double *matt,int NN,long double hx )
{
    int i,sg1,sg2;
    long double retmat[(NN+2)];
    retmat[0]=0;retmat[1]=0;retmat[NN]=0;retmat[NN+1]=0;
    for (i =2; i <=(NN-1); i++)
    {
            if (i==2){
                sg1=0;
                sg2=1;
                }
            else if (i==(NN-1)){
                sg1=1;
                sg2=0;  
                }
            else{
                sg1=1;
                sg2=1;
                }
        //===== my main formula for gradient(modified due to complication in the boundary)========
            retmat[i]=((*(matt+i)-*(matt+i-1))/hx+(*(matt+i+1)-*(matt+i))/hx)/(sg1+sg2);
            //cout <<retmat[i]<<endl;
        //========================================================================================
    }
return retmat;
}

错误消息是

saurav@sg:~/Desktop/project$ g++ test.cpp 
test.cpp: In function ‘long double* gradiv(long double*, int, long double)’:
test.cpp:23:14: warning: address of local variable ‘retmat’ returned [-Wreturn-local-addr]
  long double retmat[(NN+2)];

1 个答案:

答案 0 :(得分:0)

您正在将地址返回到本地变量if(isset($_POST['form_name']) && $_POST['form_name'] == "zone") { if(verifyForm('zone', 'add')) { $msg = array(); $msg['error'] = false; $zone_name = validate_data($_POST['zone_name']); $remark = validate_data($_POST['remark']); $errors = array(); $check = mysqli_query($conn, "SELECT zone_name FROM zone WHERE uid ='$uid' AND zone_name = '$zone_name' "); $num_check = mysqli_num_rows($check); if(isset($zone_name, $remark)) { if(empty($zone_name)) { $msg[] = 'Zone name required'; $msg['error'] = true; } elseif($num_check > 0 ) { $msg[] = 'Zone name already exists, choose another name'; $msg['error'] = true; } if(!empty($errors)) { $msg[] = '<div class="alert alert-danger">'; $msg[] = '<strong>OPPS! Correct the following error(s):</strong><br/>'; foreach($errors as $er) { $msg[] = $er.'.<br/>'; $msg['error'] = true; } $msg[] = '</div>'; } if(empty($errors) && $msg['error'] === false) { $insert = mysqli_query($conn, "INSERT INTO zone (zone_name, uid, remark) VALUES('$zone_name', '$uid', '$remark') "); if($insert) { $msg[] = 'New zone added.'; } else { $msg[] = "Can't add new zone."; $msg['error'] = true; } } } echo json_encode($msg); } } 。函数执行后变为无效。您可以通过long double retmat[(NN+2)];

为其分配内存来解决此问题
new

或者使用long double* retmat = new long double[(NN+2)]; 或其他容器与托管内存。如果您使用std::vector分配内存,则必须稍后使用new[]发布内存。