试图输出点结构c ++的坐标

时间:2016-10-29 04:54:50

标签: c++ function struct

我已经将以下结构定义为模板,用于存储点的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

任何想法为什么。

1 个答案:

答案 0 :(得分:2)

更改此行

point neighbours[4] = {};

到这个

point* neighbours = new point[4];

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