2013-01-31 110 views
0

我正在使用C.我有一個主文件,它指向一個頭文件。我打算稱之爲「主要」和後者的實施「補充」。現在當我的Main文件運行時,它會從我的Supplement中調用一個函數。C Global Struct

該函數mallocs和編輯一個全局變量(在我的Supplement文件中)。繼續前進,我再次從我的Supplement文件中調用另一個函數。

現在這是問題所在,因爲每當我這樣做時我都會收到分段錯誤。使用gcc,我能夠發現在我的第二次函數調用期間,我編輯的全局變量似乎'消失'(打印顯示它在0x0地址並且不能訪問)。

I在C中是相當新的,我知道全局變量是不好的,但這是一個任務,因爲我們不能編輯Main文件,所以我只能在我的補充文件中使用全局變量來記住我的變量。

切割代號:

Main: 
    // call load 
// check 

Supplement: 

    typedef struct node 
{ 
    bool is_word; 
    struct node* children[27]; 
}node; 

//Root Node 
static node* root = NULL; 

bool check(const char* word) 
{ 
    //edits word and puts it into input[i](as int) 
    for(int i=0;i<x;i++) 
    { 
     //uses root[input[i]] -this is the problem. Apparently root is 0x0. 
    } 
} 

bool load(const char* dictionary) 
{ 
    //mallocs and edits root. Note that it is quite a handful. Do note that in the context of this function, gdb returns seems to know root. It's just on the check function call that it mysteriously disappears. 

//current = root 

node* cur = root; 
root = malloc(sizeof(node)); 

//Check if opened 
if(dict==NULL) 
{ 
    return false; 
}else 
{ 
    int ch = getc(dict); 
    while(ch!=EOF) 
    { 
     //if character is newline 
     if(ch==10) 
     { 
      cur->is_word = true; 
      cur = root; 
      dSize++; 
     }else{ 
      int value = (ch==APOST)? 26 : ch-ASCII; 
      //if there are no nodes yet 
      if(cur->children[value]==NULL) 
      { 
       //make a new node 
       node* next = malloc(sizeof(node)); 
       //point children to node 
       cur->children[value]= next; 
       //current becomes new node 
       cur= next; 
      }else{ 
      //else, use node 
       cur=cur->children[value]; 
      } 
     } 
     ch = getc(dict); 
    }; 
    return true; 
} 

} 

我其實設置root的變量。我不確定爲什麼我的代碼會引發這樣的評論。 我也通過在gdb上打印根證實了這一點。唯一的問題是在加載完成後,我運行檢查,root不見了。 在此先感謝!

+2

你可以發佈一個最小的工作職能給予該變量的引用顯示問題的代碼示例? – Bakuriu

+0

顯示代碼,比敘述更好。 – UmNyobe

+0

你可以讓[SSCCE](http://sscce.org/)向我們展示?如果我們可以看到一些代碼,這會更容易。它甚至可以幫助你自己找到問題。 –

回答

1

我不知道爲什麼你在你的特定情況下出現錯誤,因爲你沒有顯示任何代碼。然而,適當辦法做到這一點是:

的main.c

#include "supp.h" 
#include <stdio.h> 

int main() 
{ 
    set_x (5); 
    printf("%d", get_x()); 
    return 0; 
} 

supp.h

#ifndef SUPP_H 
#define SUPP_H 

void set_x (int n); 
int get_x (void); 

#endif /* SUPP_H */ 

supp.c

#include "supp.h" 

static int x; 

void set_x (int n) 
{ 
    x = n; 
} 

int get_x (void) 
{ 
    return x; 
} 

該代碼使用c文件中的「文件範圍」靜態變量。您不能直接從任何其他文件訪問x。這被稱爲專用封裝,它總是很好的編程實踐和部分概念,稱爲面向對象的程序設計。

+0

是的,但是讓我感到困惑的是,我似乎無法從我的文件中使用全局變量,因爲當我轉到另一個函數時,它似乎'忘記'我編輯了全局變量。 – Secret

0

沒有理由使用全局變量,你可以在主聲明變量() 然後使用它

bool load(node** root, const char* dictionary); 
bool check(node* root, const char* word); 

int main() 
{ 
    node* root = NULL; 

    load(&root, dictionary); 

    ... 
    if (check(node,word)) 
    { 
    ... 
    } 
} 
+0

我無法編輯函數調用。看來這需要一個函數調用編輯。如果我錯了,請糾正我。PS:除非你明確告訴我,否則我永遠不會知道另一個文件的主體即使不是程序運行也會運行!謝謝! – Secret