【问题标题】:Why I cannot break the value assignment into two different statements?为什么我不能将值分配分成两个不同的语句?
【发布时间】:2017-02-06 17:17:34
【问题描述】:
   #inlude <stdio.h>
   typedef struct node
   {
     int data, height, count;
     struct node *left, *right, *father;
   }node;
   node *root = NULL;
   void main(){
   //some code here
   }

上面的代码没有错误,但是

  #inlude <stdio.h>
   typedef struct node
   {
     int data, height, count;
     struct node *left, *right, *father;
   }node;
   node *root;
   root = NULL;
   void main(){
   //some code here
   }

这会产生以下错误:

sample.c:11:1: error: conflicting types for 'root' 
sample.c: 10:7 note: previous declaration of 'root' was here 
node *root; 
      ^

上述错误在语句时没有重现

root = NULL;

main function内声明

可能是什么原因?

【问题讨论】:

  • 当变量不是初始化的一部分时,您不能只在函数外部分配一个变量。
  • 请注意,所有全局变量都是零初始化的,没有必要像你一样将它们重新初始化为零。

标签: c pointers null initialization variable-assignment


【解决方案1】:

在第一种情况下,

 node *root = NULL;

是一个 initialization while 声明。这在全局范围内是明确允许的。

另一方面,

node *root;
root = NULL;

是一个声明一个assignment,后者是要执行的语句,它必须在某个函数范围内。它不能驻留在全局范围内。

因此,在您的情况下,root 是一个全局变量,可以从 main() 完全访问,并且赋值语句在那里也是合法的。没有抱怨。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多