试图输出点结构体的坐标
Attempting to output the coordinates of point structs c++
我定义了以下结构体作为模板来存储点的x和y坐标:
typedef struct point {
int x_coordinate, y_coordinate;
};
我还定义了以下函数:
point* get_neighbours(point p) {
point neighbours[4] = {};
point left_neighbour, right_neighbour, upper_neighbour, lower_neighbour;
left_neighbour.x_coordinate = p.x_coordinate - 1;
left_neighbour.y_coordinate = p.y_coordinate;
neighbours[0] = left_neighbour;
right_neighbour.x_coordinate = p.x_coordinate + 1;
right_neighbour.y_coordinate = p.y_coordinate;
neighbours[1] = right_neighbour;
upper_neighbour.x_coordinate = p.x_coordinate ;
upper_neighbour.y_coordinate = p.y_coordinate+1;
neighbours[2] = upper_neighbour;
lower_neighbour.x_coordinate = p.x_coordinate;
lower_neighbour.y_coordinate = p.y_coordinate - 1;
neighbours[3] = lower_neighbour;
return neighbours;
}
但是,当我执行以下代码时:
point the_point;
the_point.x_coordinate=3;
the_point.y_coordinate=3;
point* neighbours=get_neighbours(the_point);
for (int i = 0; i < 4; i++) {
cout << neighbours[i].x_coordinate << " " << neighbours[i].y_coordinate << "n";
}
得到以下输出:
2 3
-858993460 0
-858993460 0
14677568 14678244
知道为什么吗?
改变这一行
point neighbours[4] = {};
point* neighbours = new point[4];
它必须在堆上分配,因为你的是在函数的堆栈上分配的,所以它将在函数退出时丢失。
相关文章:
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 包含 std::list 的结构体的 C++ 初始化
- 结构体和类的不同大小(),彼此具有相同的字段类型
- 如何使用结构体的向量数组?
- 如何使用结构体在C++中更改这些代码?
- 无法在 Mosquitto MQTT Broker 插件上访问结构体 mosquitto 的元素
- 我应该如何在C++中使用结构体解决输入失败的问题?
- Qsort() 比较结构体整数的总和
- 如何使用迭代器指向结构体c++的向量
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 如何获取结构体成员的地址
- 创建结构体向量,表达式:向量下标超出范围
- 对坐标结构的向量进行排序
- boost::任何带有结构体和无符号整数
- 如何在构造函数中初始化结构体的动态数组?
- 只写结构体的某些字段
- C++ push_back() 一个结构体到一个向量中
- 试图输出点结构体的坐标