2016-09-28 35 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

相關問題