gpt4 book ai didi

c - 全局和函数中的不同初始化和符号指针值

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

我知道关于这个问题我会被降很多分,但我还是写了下面的测试代码:

int *gPtr;
//I know I can NOT write below code line, but I need know WHY
gPtr = NULL;//or some other value which I want to init it
//int *gPtr = NULL; //this line should be OK

int main (void)
{
int *ptr;
ptr = NULL;
return 0;
}

编译时全局的*gPtr会输出错误:

ptr.c:4:1: warning: data definition has no type or storage class [enabled by default]
ptr.c:4:1: error: conflicting types for ‘gPtr’
ptr.c:3:6: note: previous declaration of ‘gPtr’ was here
ptr.c:4:8: warning: initialization makes integer from pointer without a cast [enabled by default]

然而,在函数中,我做了同样的代码,但没有编译错误/警告,我想知道:

  • 在全局和函数中对一个值进行签名有什么不同。
  • 为什么编译器不允许我在全局区域中签名。
  • int a = 0;int a; 有什么不同? a=0;//这两句之间没有其他代码

请根据编译器的观点(或者您认为它应该在编码标准等其他观点中有其他解释?)给我建议以上三个问题?

最佳答案

您可以定义一个具有初始值的全局变量:

int *gPtr = NULL;

但是您不能在函数范围之外进行赋值。编译器(好吧,至少我的 clang 编译器)实际解释

gPtr = NULL;

在全局范围内作为

int gPtr = NULL;

这会导致类似的警告和类型冲突的错误:

warning: type specifier missing, defaults to 'int' [-Wimplicit-int]gPtr = NULL;^~~~error: redefinition of 'gPtr' with a different type: 'int' vs 'int *'note: previous definition is hereint *gPtr;

Global variable without an explicit initial value are automatically initializedto zero, therefore in your case

int *gPtr;

就足够了(正如@WhozCraig 已经在上面评论过的那样)。

关于c - 全局和函数中的不同初始化和符号指针值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21362340/

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