不要在文件作用域赋值(C Primer Plus学习笔记)

文件作用域中不能赋值!!

在学习结构体的相关知识时,我定义了一个结构体变量,定义了一个指向结构体的指针

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
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值