struct.field returns 另一个值,为什么?
struct.field returns another value, why?
我的目标是创建一个 fisrt
我的自定义 struct
类型。
当 运行 时,打印出 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);
}
您忘记从 new_one()
到 return
。
相关阅读:来自第 6.9.1 章第 12 段,C11
文档,
If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
因此,在您的代码中,没有来自 new_one()
的 return
并且通过 printf("%d\n",first.number);
访问 return 值,您将面临 undefined behaviour .
此外,值得一提的是,main()
的正确语法是 int main()
,(匹配 return 0
是一个很好的做法。)
您需要添加一个
return a;
在您的 new_one() 函数中,以便从函数 new_one()
返回结构
我的目标是创建一个 fisrt
我的自定义 struct
类型。
当 运行 时,打印出 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);
}
您忘记从 new_one()
到 return
。
相关阅读:来自第 6.9.1 章第 12 段,C11
文档,
If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
因此,在您的代码中,没有来自 new_one()
的 return
并且通过 printf("%d\n",first.number);
访问 return 值,您将面临 undefined behaviour .
此外,值得一提的是,main()
的正确语法是 int main()
,(匹配 return 0
是一个很好的做法。)
您需要添加一个
return a;
在您的 new_one() 函数中,以便从函数 new_one()
返回结构