2013-01-31 67 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