簡體   English   中英

函數返回指向數組的指針

[英]function returns pointer to array

我編寫了此C ++代碼,以使函數返回指向double數組的指針,以這種方式,我將其用作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:\Users\laptop\Desktop\C_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.0\VC\INCLUDE\xlocale(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;
}

試試這個,那是什么問題? 您的函數原型和簽名不匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM