函数返回指向数组的指针

function returns pointer to array

本文关键字:指针 数组 返回 函数      更新时间:2023-10-16

我编写了这个 C++ 代码来使函数返回指向双精度数组的指针,这样我就将其用作 rvalue。我收到一条奇怪的错误消息,因为我无法理解它有什么问题。这是带有错误消息的代码

#include <iostream>
using std::cout;
using std::endl;
double* fct_returns_ptr(double, int); // function prototype
int main(void)
{
    double test_array[] = { 3.0, 10.0, 1.5, 15.0 }; // test value
    int len = (sizeof test_array)/(sizeof test_array[0]);
    //double* ptr_result = new double(0.0); //[len]  pointer to result
    double* ptr_result = new double[len]; // (0.0) pointer to result
    ptr_result = fct_returns_ptr(test_array, len);
    for (int i=0; i<len; i++)
        cout << endl << "Result = " << *(ptr_result+i); // display result
    cout << endl;
    delete [] ptr_result; // free the memory
    return 0;
}
// function definition
double* fct_returns_ptr(double data[], int length)
{
    double* result = new double(0.0);
    for (int i=0; i<length; i++)
        *(result+i) = 3.0*data[i];
    return result;
}
/*
C:UserslaptopDesktopC_CPP>cl /Tp returns_ptr.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 16.00.40219.01 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.
returns_ptr.cpp
c:Program Files (x86)Microsoft Visual Studio 10.0VCINCLUDExlocale(323) : warning C4530: C++ 
exception handler used, but unwind semantics are not enabled. Specify /EHsc
returns_ptr.cpp(13) : error C2664: 'returns_ptr' : cannot convert parameter 1 from 'double [4]' to 'double'
        There is no context in which this conversion is possible
*/

fct_returns_ptr()中,行double* result = new double(0.0);不会创建双精度数组,而是创建一个起始为 0.0 的双指针。 我怀疑你的意思是:

double* result = new double[length];

你也不需要

double* ptr_result = new double[len]; // (0.0) pointer to result
ptr_result = fct_returns_ptr(test_array, len);

在函数中创建数组时main()。您可以将其更改为:

double* ptr_result = fct_returns_ptr(test_array, len);
#include <iostream>
using namespace std;
double* fct_returns_ptr(double  *, int); // function prototype
int main(void)
{
    double test_array[] = { 3.0, 10.0, 1.5, 15.0 }; // test value
    int len = (sizeof test_array)/(sizeof test_array[0]);
    //double* ptr_result = new double(0.0); //[len]  pointer to result
    double* ptr_result = new double[ len ] ;
    ptr_result = fct_returns_ptr(test_array, len);
    for (int i=0; i<len; i++)
        cout << endl << "Result = " << *(ptr_result+i); // display result
    cout << endl;
    delete [] ptr_result; // free the memory
    return 0;
}
// function definition
double* fct_returns_ptr(double *data, int length)
{
    double* result = new double[length];
    for (int i=0; i<length; i++)
        *(result+i) = 3.0*data[i];
    return result;
}

试试这个,有什么问题?您的函数原型和签名不匹配。