试图输出点结构体的坐标

Attempting to output the coordinates of point structs c++

本文关键字:坐标 结构体 出点 输出      更新时间:2023-10-16

我定义了以下结构体作为模板来存储点的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];

它必须在堆上分配,因为你的是在函数的堆栈上分配的,所以它将在函数退出时丢失。