gpt4 book ai didi

c - 当涉及功能时,结构、 union 等的范围如何工作?

转载 作者:太空宇宙 更新时间:2023-11-04 01:17:26 24 4
gpt4 key购买 nike

我最近遇到了一些结构,有些事情不是很清楚。假设我有这样一个程序:

struct num print_a(struct num c); 

int main(){
struct num{
int a;
int b;
}c = {1, 2};
struct num d;
d = print_a(c);
}

struct num print_a(struct num c){
printf("%d", c.a);
return c;
}

这行得通吗,还是我必须在 main 之外声明 struct num?因为我的函数 print_a 如何“看到”struct num 的含义(它必须返回的类型),因为它在其范围之外声明?

对不起,如果这个问题很愚蠢

最佳答案

Would this work or do I have to declare struct num outside of main?

那么,为什么不简单地尝试一下呢?

http://ideone.com给出:

Compilation error #stdin compilation error #stdout 0s 9424KB
prog.c: In function ‘main’:
prog.c:11:15: error: type of formal parameter 1 is incomplete
d = print_a(c);
^
prog.c:11:3: error: invalid use of undefined type ‘struct num’
d = print_a(c);
^
prog.c:10:14: warning: variable ‘d’ set but not used [-Wunused-but-set-variable]
struct num d;
^
prog.c: At top level:
prog.c:14:31: error: parameter 1 (‘c’) has incomplete type
struct num print_a(struct num c){
^
prog.c:14:12: error: return type is an incomplete type
struct num print_a(struct num c){
^~~~~~~
prog.c:14:12: error: conflicting types for ‘print_a’
prog.c:3:12: note: previous declaration of ‘print_a’ was here
struct num print_a(struct num c);
^~~~~~~
prog.c: In function ‘print_a’:
prog.c:16:10: warning: ‘return’ with a value, in function returning void
return c;
^
prog.c:14:12: note: declared here
struct num print_a(struct num c){
^~~~~~~

http://coliru.stacked-crooked.com/给出:

main.cpp: In function 'main':
main.cpp:13:15: error: type of formal parameter 1 is incomplete
d = print_a(c);
^
main.cpp:13:7: error: invalid use of undefined type 'struct num'
d = print_a(c);
^~~~~~~
main.cpp:12:14: warning: variable 'd' set but not used [-Wunused-but-set-variable]
struct num d;
^
main.cpp: At top level:
main.cpp:16:31: error: parameter 1 ('c') has incomplete type
struct num print_a(struct num c){
~~~~~~~~~~~^
main.cpp:16:12: error: return type is an incomplete type
struct num print_a(struct num c){
^~~~~~~
main.cpp:16:12: error: conflicting types for 'print_a'
main.cpp:5:12: note: previous declaration of 'print_a' was here
struct num print_a(struct num c);
^~~~~~~
main.cpp: In function 'print_a':
main.cpp:18:10: warning: 'return' with a value, in function returning void
return c;
^
main.cpp:16:12: note: declared here
struct num print_a(struct num c){
^~~~~~~

嗯...有点给我们答案:不 - 它不会工作

当您在 main 中定义结构时,它仅在 main 中为人所知。如果你想在 main 之外使用结构,你必须将结构的定义移出 main - 比如:

struct num {
int a;
int b;
};

struct num print_a(struct num c);

int main(){
struct num c = {1, 2};
struct num d;
d = print_a(c);
}

struct num print_a(struct num c){
printf("%d", c.a);
return c;
}

关于c - 当涉及功能时,结构、 union 等的范围如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54495032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com