【问题标题】:Member of struct wont stock in a variablestruct 的成员不会存储在变量中
【发布时间】:2017-11-20 13:49:13
【问题描述】:

我今天的代码有问题, 问题看起来像这样:

void my_function(r_struct *suit) 
{
     sfVector2f position;

     position = get_position(suit->other_vector);
     printf("Output : %f\n", position.x);
}

(get_position 返回一个 sfVector2f) 当我这样做时,位置的输出是:0。 但是当我这样做时:

void my_function(r_struct *suit)
{
     printf("Output: %f\n", get_position(suit->other_vector).x);
}

现在输出是:50。我不明白我做错了什么

编辑:

sfVector2f *get_position(sfVector2f *point_to)
{
     sfVector2f new_pos;
     new_pos.x = point_to.x;
     new_pos.y = point_to.y;
     return (new_pos);
}

【问题讨论】:

  • 请提供get_position()函数的代码。
  • 无意冒犯,但这很难相信。一个独立的完整可编译示例的好案例。
  • 顺便说一句,用r_struct 之类的名称键入struct 确实毫无意义,原因有很多。
  • 我看不到显示的函数是如何编译的。您从应该返回指针的函数返回结构。返回指向局部变量的指针将是未定义的行为。返回一个结构是干净和简单的。

标签: c struct output


【解决方案1】:

您不能返回指向局部变量的指针,当您退出函数时,该变量将被销毁并且它所保存的值将丢失。 如果您返回 sfVector2f,它应该可以按预期工作并且它所持有的值是 b。

sfVector2f get_position(sfVector2f *point_to)
{
     sfVector2f new_pos;
     new_pos.x = point_to.x;
     new_pos.y = point_to.y;
     return (new_pos);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 2011-01-01
    相关资源
    最近更新 更多