2016-09-28 36 views
0
#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

可能是什么原因?

+4

当函数不是初始化的一部分时,您不能只在函数之外分配一个变量。 –

+0

请注意,所有全局变量都是零初始化的,将它们重新初始化为零就没有意义了。 –

回答

7

在第一种情况下,

node *root = NULL; 

initialization而声明。这在全球范围内是明确允许的。

在另一方面,

node *root; 
root = NULL; 

是一个声明assignment,后来被要执行的语句,它必须是在一些功能范围。它不能驻留在全球范围内。

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

+0

yup,kv manohar这是你的问题的答案:) – SMW

相关问题