对于我的小型任务,在30层的建筑中,我必须收集人们在电梯中按下的地板,然后找出每个地板之间的差异。
因此,我计划设置一个30层的数组(我们仅被告知数组是我们的唯一容器)。电梯中的人员将单击电梯的按钮,因此假设(5,10,14,19,29)。
然后,我计划将此数组传递给一个函数,该函数将计算每个楼层之间的差异。
到目前为止,这是我的代码,我知道它是错误的,因为它没有编译,在其他地方也可能是错误的。
这是错误消息:
CODE
#include <iostream>
#include <numeric>
#include <algorithm>
using std::cout;
using std::endl;
int* calculateDiff(int floors[], int floorsSize);
int main()
{
int floorsPressed[30] = {5, 10, 14, 19, 29};
int floorsCounter = 5;
int* ptr = calculateDiff (floorsPressed, floorsCounter);
int floorsDiffResult[30];
for (int i = 0; i < floorsCounter; i++)
{
floorsDiffResult[i] = *(ptr + i); //Storing the difference into floorsDiffResult array
cout << "Difference: " << *(ptr + i) << endl;
}
}
int* calculateDiff(int floors[], int floorsSize)
{
int floorsDiffResult[30]; //Create another array to store the difference for other calculations later on such as finding the biggest difference, average of the difference etc.
std::adjacent_difference(floors, floors + floorsSize, floorsDiffResult);
std::move(floors + 1, floors + floorsSize, floorsDiffResult); //First element does not give the difference
return floorsDiffResult;
}
最佳答案
我不知道您要在此处执行的操作背后的逻辑是否正确,但是这里存在一个主要问题,您正在返回指向局部变量的指针!
这是未定义的行为,因为它是局部的,并且生存期受限于您的函数范围,此后任何事情都可能发生,甚至是您期望的事情(正确的结果)。
因此,您可以改用以下方法:
int* calculateDiff(int floors[], int* output, int floorsSize);
int main()
{
int floorsPressed[30] = {5, 10, 14, 19, 29};
int floorsReturn[30] = {};
int floorsCounter = 5;
int* ptr = calculateDiff(floorsPressed, floorsReturn, floorsCounter);
int floorsDiffResult[30];
for(int i = 0; i < floorsCounter; i++)
{
floorsDiffResult[i] = *(ptr + i); //Storing the difference into floorsDiffResult array
cout << "Difference: " << *(ptr + i) << endl;
}
}
int* calculateDiff(int floors[], int* output, int floorsSize)
{
//int floorsDiffResult[30]; //Create another array to store the difference for other calculations later on such as finding the biggest difference, average of the difference etc.
std::adjacent_difference(floors, floors + floorsSize, output);
std::move(floors + 1, floors + floorsSize, output); //First element does not give the difference
return output;
}
而且您不需要从
calculateDiff
返回一个指针,floorsReturn
将在函数执行后得到您的结果,但是我不想做太多改变。关于c++ - 将数组传递给函数并返回指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49808282/