我正在使用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不见了。 在此先感谢!
你可以发布一个最小的工作职能给予该变量的引用显示问题的代码示例? – Bakuriu
显示代码,比叙述更好。 – UmNyobe
你可以让[SSCCE](http://sscce.org/)向我们展示?如果我们可以看到一些代码,这会更容易。它甚至可以帮助你自己找到问题。 –