文件作用域中不能赋值!!
在学习结构体的相关知识时,我定义了一个结构体变量,定义了一个指向结构体的指针
struct name{
char first[20];
char last[20];
};
struct name yichen = {
"yichen",
"guannan"
};
struct name *ptr;
我想让指针指向结构体变量 ptr = &yichen;
编译器的时候报错了,报错信息如下:
test.c:14:5: warning: data definition has no type or storage class
14 | ptr = &yichen;
| ^~~
test.c:14:5: warning: type defaults to ‘int’ in declaration of ‘ptr’ [-Wimplicit-int]
test.c:14:5: error: conflicting types for ‘ptr’
test.c:13:18: note: previous declaration of ‘ptr’ was here
13 | struct name *ptr;
| ^~~
test.c:14:11: warning: initialization of ‘int’ from ‘struct name *’ makes integer from pointer without a cast [-Wint-conversion]
14 | ptr = &yichen;
| ^
test.c:14:11: error: initializer element is not computable at load time
test.c: In function ‘main’:
test.c:19:25: error: invalid type argument of ‘->’ (have ‘int’)
19 | printf("%s %s\n",ptr->first,ptr->last);
| ^~
test.c:19:36: error: invalid type argument of ‘->’ (have ‘int’)
19 | printf("%s %s\n",ptr->first,ptr->last);
| ^~
然而当我在定义指针的时候直接让他指向结构体变量就没问题:
struct name *ptr = &yichen;
搜了一下发现是因为 ptr = &yichen;
这条语句是放在文件作用域中的,对于编译器来说这条语句不在函数内部,因此不是代码,更像是在定义一个变量,而默认类型是 int,所以这就相当于:
int ptr = &yichen;
解决方法就是把 ptr = &yichen;
这条语句放在 main 函数里面喽
搜到的资料:
https://stackoverflow.com/questions/56091344/why-am-i-getting-compilation-error-error-conflicting-types-for-ptr-for-the
https://stackoverflow.com/questions/50661263/why-cant-i-assign-values-to-global-variables-outside-a-function-in-c