错误的指向数组的函数返回一个指针 [英] Error in returning a pointer from a function that points to an array
问题描述
我是有点在小提琴,我不知道为什么我的code带来了编译时出现以下错误:
I'm in a bit of a fiddle in that I don't know why my code brings up the following error when compiling:
1>..\SA.cpp(81) : error C2664: 'CFE' : cannot convert parameter 1 from 'int' to 'int []'
1> Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
从本质上讲,我想:
Essentially I am trying to:
第一步:从使用向量转换为一个数组:
Step1: Convert from a vector to an array using:
int* VecToArray(vector<int> Vec)
{
int ary[Vec.size()];
for(int i = 0; i < Vec.size(); i++)
ary[i] = Vec[i];
return ary;
}
第二步:在调用一个函数到其中的阵列是paremeter,它从一个新生成的数组返回一个指针:
Step2: Calling upon a function into which the array is an paremeter and it returns a pointer from a newly generated array:
int* CFE(int density[])
{
...do stuff to generate 'double Energy[]'....
return Energy;
}
步骤3:在第三函数使用该指针calcualte能量的总和[]:
Step 3: Using this pointer in a third function to calcualte the sum of Energy[]:
double ObjFunction (double *E_Array)
{
double SumEnergy = 0;
int n = 10; // Is irrelivant
for (int i = 0; i < n; i++)
{
SumEnergy += E_Array[i];
}
return SumEnergy;
}
要做出简单的编码我用的功能,像这样,在VectorName是一个整数向量:
To make for simpler coding I've used the functions like so, where VectorName is an integer vector:
double TotalEnergy = ObjFunction ( CFE ( VecToArray ( VectorName ) ) );
我明明收到的参数类型不对的地方,但我只是不能明白为什么自己。任何人都可以用一个更有经验的眼睛在发现它/它们帮助?
I am obviously getting the parameter types wrong somewhere, though I just cant see why myself. Could anyone with a more experienced eye assist in spotting it/them?
推荐答案
哪里能源
从何而来?如果它是一个双[]
,那么你不能只是将其转换为为int *
。
Where does Energy
come from? If it's a double[]
then you can't just cast it to an int*
.
的std ::矢量&lt; INT&GT;
保证是连续的,所以如果你想转换一个的std ::矢量&lt; INT&GT; VectorName
到 const int的*
使用&放大器; VectorName [0]
。如果,另一方面,您的CFE函数修改数组传递,它可能会更好过本地创建它。
std::vector<int>
is guaranteed to be contiguous, so if you want to convert a std::vector<int> VectorName
to an const int*
use &VectorName[0]
. If, on the other hand, your CFE function modifies the array is passed, it's probably better off creating it locally.
这篇关于错误的指向数组的函数返回一个指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!