C全球结构

时间:2013-01-31 10:20:24

标签: c

我正在使用C.我有一个Main文件,它指向一个头文件。我将打电话给前'主'和后者的实施'补充'。现在,当我的Main文件运行时,它会从我的Supplement中调用一个函数。

该函数mallocs并编辑一个全局变量(在我的Supplement文件中。)继续,我再次从我的Supplement文件调用另一个函数。

现在这就是问题所在,因为每当我这样做时,我都会收到Segmentation故障。使用gcc,我能够发现在我的第二个函数调用我的Supplement期间,我编辑的全局变量看似“消失”(打印使它显示它位于0x0地址且无法访问。)

我是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;
}

}

我实际上是在设置根变量。我不确定为什么我的代码会引起这样的评论。 我也通过在gdb上打印root来确认这一点。唯一的问题是在完成加载后,我正在运行检查,root已经消失。 在此先感谢!

2 个答案:

答案 0 :(得分: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。这称为私有封装,它总是很好的编程实践,也是称为面向对象程序设计的概念的一部分。

答案 1 :(得分:0)

没有理由使用全局变量,你可以在main()中声明变量 然后将该变量的引用提供给使用它的函数

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) ) 
  {
  ...
  }
}