【问题标题】:c struct pointers and scope confusionc结构指针和范围混淆
【发布时间】:2014-09-10 11:33:24
【问题描述】:

我有一个由 3 个文件组成的程序。

  • main.c 包含堆栈的外部变量,并包含解析输入并将输入传递给 stack.c 中的函数的代码

  • stack.c //包含执行堆栈推/拉等操作的函数

  • stack.h //包含函数原型

程序目前使用全局整数数组作为栈。

我现在尝试将程序转换为使用堆栈的链表而不是整数数组。

我的问题是我不知道应该在哪里声明结构以及应该在哪里声明结构成员。我应该把它们放在 main 函数之外的 main.c 中,在 stack.h 头文件中吗?

我的结构声明

struct node {
   int value;
   struct node *next;
};

struct node *first = NULL;
struct node *new_node = NULL;


new_node = malloc(sizeof(struct node));

【问题讨论】:

  • 结构定义和指针声明可以保持全局。 new_node = malloc(sizeof(struct node)); 必须在函数内部(例如 main()),因为它生成“代码”,而不是“数据”。
  • 我不确定为什么链表堆栈需要两个指针。

标签: c


【解决方案1】:

stack.c

#include "stack.h"
struct node *first = NULL;
struct node *new_node = NULL;

stack.h

struct node {
   int value;
   struct node *next;
};

extern struct node *first;
extern struct node *new_node;

main.c

#include "stack.h"
//inside main
//new_node = malloc(sizeof(struct node)); //don't forgot to free it

【讨论】:

    【解决方案2】:

    排除任何关于全局变量的争论,我看到两个选项:

    1) 只在stack.c 中定义你的结构,然后在stack.h 中声明它:

    /*stack.h*/
    struct node;
    
    extern struct node *g_first_node = NULL;
    extern struct node *g_new_node = NULL;
    

    2) 将结构体定义放在stack.h中,所有引用它的代码都可以使用。

    【讨论】:

      【解决方案3】:

      将您的结构定义和外部变量声明放在头文件中,并将您的头文件包含在其他.c 文件中。 [不要忘记添加标题保护(include guard)]。

      然后,在您的main.c [并在stack.c 文件中使用] 中创建结构类型的变量。这是常见的类比。

      示例

      //stack.h
      struct node {
         int value;
         struct node *next;
      };
      
      extern struct node *g_first_node;
      extern struct node *g_new_node;
      

      那么,在main.c

      #include "stack.h"
      struct node *g_first_node= NULL;
      struct node *g_new_node= NULL;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-25
        • 2011-09-04
        • 2016-11-08
        • 2011-12-22
        • 1970-01-01
        • 2014-11-18
        • 1970-01-01
        相关资源
        最近更新 更多