[英]Wrong output on c++ arrays
I am fairly new to C++ so this question may seem very basic(dumb.), I am trying to return an array of (int i. int j) which is a position(coordinates).我对 C++ 相当陌生,所以这个问题可能看起来很基本(愚蠢。),我试图返回一个 (int i. int j) 数组,它是一个位置(坐标)。
Here is my code:这是我的代码:
int* Unblocker(int d1[2],int d2[2])
{
int unblocker_position[2];
int distance;
distance = abs(d1[0]-d2[0])+ abs(d1[1]-d2[1]);
switch (distance)
{
case 1:
break;
case 2:
switch (abs(d1[0] - d2[0]))
{
case 2:
unblocker_position[0] = 1;
unblocker_position[1] = 0;
return unblocker_position;
break;
default:
return NULL;
break;
}
break;
default:
return NULL;
break;
}
}
int main(){
int p1[2]={0,0};
int p2[2]={2,0};
int * a = Unblocker(p1,p2);
cout << a[0] << " " << a[1] << endl;
return 0;}
The output is: output 是:
1 1
however, I expect "1 0".但是,我希望“1 0”。 I am not sure if I made a mistake using a switch or in using an array as the return type.我不确定是使用开关还是使用数组作为返回类型时出错了。 I removed other cases in the switch to make it easier to get to the point.我删除了 switch 中的其他案例,以便更容易理解。
If you want to return a pointer to a local variable you need to store the variable in the heap.如果要返回指向局部变量的指针,则需要将该变量存储在堆中。 To do so you have to use the new
operator.为此,您必须使用new
运算符。
int *Unblocker(int d1[2], int d2[2])
{
int *unblocker_position = new int[2];
int distance;
distance = abs(d1[0] - d2[0]) + abs(d1[1] - d2[1]);
switch (distance)
{
case 1:
break;
case 2:
switch (abs(d1[0] - d2[0]))
{
case 2:
unblocker_position[0] = 1;
unblocker_position[1] = 0;
return unblocker_position;
break;
default:
return NULL;
break;
}
break;
default:
return NULL;
break;
}
return NULL;
}
int main()
{
int p1[2] = {0, 0};
int p2[2] = {2, 0};
int *a = Unblocker(p1, p2);
cout << a[0] << " " << a[1] << endl;
delete a;
return 0;
}
Remember to use the delete operator to prevent memory leaks.请记住使用删除运算符来防止 memory 泄漏。
If you want to learn more about this topic I suggest you look at smart pointers .如果您想了解有关此主题的更多信息,我建议您查看智能指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.