简体   繁体   English

struct.field返回另一个值,为什么?

[英]struct.field returns another value, why?

My goal is to create an fisrt of my custom struct type. 我的目标是创建一个自定义struct类型的fisrt器。 When run, prints out 24. Can't understand why: 运行时,将输出24。无法理解原因:

#include <stdio.h>
typedef struct strktura {
    int number;
    char name;
} strktura;

strktura new_one(int number, char name){
    strktura a;
    a.number=number;
    a.name=name;
}

main()
{
        strktura first=new_one(2,"A");
        printf("%d\n",first.number);
}

You forgot to return from new_one() . 您忘记了从new_one() return

Related Reading: From chapter 6.9.1, paragraph 12, C11 document, 相关阅读:来自C11文件6.9.1节,

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined. 如果到达终止函数的},并且调用者使用了函数调用的值,则该行为未定义。

So, in your code, without a return from new_one() and by accessing the return value through printf("%d\\n",first.number); 因此,在您的代码中,无需从new_one() return ,而可以通过printf("%d\\n",first.number);访问返回值printf("%d\\n",first.number); , you're facing undefined behaviour . ,您将面临不确定的行为

Also, worthy to mention, the correct syntax for main() is int main() , (and a matching return 0 is a good practice.) 另外,值得一提的是, main()的正确语法是int main() ,并且匹配的return 0是一个好习惯。

You need to add a 您需要添加一个

return a;

in your new_one() function so that the structure gets returned from the function new_one() 在您的new_one()函数中,以便从函数new_one()返回结构

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM