对于我的迷你作业,在一栋 30 层的建筑物中,我必须收集人们在电梯中按的楼层,然后找出每个楼层之间的差异。
所以,我打算设置一个 30 层的数组(我们只被教导数组作为我们唯一的容器)。电梯里的人会点击电梯的按钮,假设是 (5, 10, 14, 19, 29)。
然后我计划将这个数组传递给一个函数,该函数将计算每层楼之间的差异。
到目前为止,这是我的代码,我知道它是错误的,因为它没有编译,我也可能在其他地方错了。
这是错误信息:
main.cpp: In function 'int* calculateDiff(int*, int)': main.cpp:26:7: warning: address of local variable 'floorsDiffResult' returned [-Wreturn-local-addr]
代码
#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/