gpt4 book ai didi

C 结构指针和作用域混淆

转载 作者:行者123 更新时间:2023-11-30 15:30:09 24 4
gpt4 key购买 nike

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

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

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

  • stack.h//包含函数原型(prototype)

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

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

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

我的结构声明

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

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


new_node = malloc(sizeof(struct node));

最佳答案

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

关于C 结构指针和作用域混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25764325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com