我正在尝试实现堆栈的数组实现。我刚开始使用堆栈,我尝试在c中实现push操作,下面是我的代码:
#include "stack.h"
/**
* push_arr_stack - pushes an element to the stack
* @n: The number that will be pushed to the stack
*
* Return: It returns nothing
*
*/
void push_arr_stack(int n)
{
top = top + 1;
stack_arr[top] = n;
}以下是我的头文件:
#ifndef STACK_H
#define STACK_H
#define MAX 4
extern int stack_arr[MAX];
extern int top = -1;
void push_arr_stack(int n);
#endif 我使用以下测试函数尝试了push操作:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
/**
* main - Entry point for my program
*
* Return: On success, it returns 0,
* On error, it returns -1
*/
int main(void)
{
push_arr_stack(7);
return (0);
}但我得到了以下错误
gcc -Wall -Werror -Wextra -pedantic -std=gnu89 main.c 0-push_arr_stack.c
In file included from main.c:4:
stack.h:6:12: error: ‘top’ initialized and declared ‘extern’ [-Werror]
6 | extern int top = -1;
| ^~~
cc1: all warnings being treated as errors
In file included from 0-push_arr_stack.c:1:
stack.h:6:12: error: ‘top’ initialized and declared ‘extern’ [-Werror]
6 | extern int top = -1;
| ^~~
cc1: all warnings being treated as errors我需要顶级变量来跟踪哪个索引是堆栈的顶部,但是它给了我初始化和声明top的错误。如何才能将top初始化为-1
发布于 2022-09-07 12:46:36
头文件包含在两个翻译单元中: with main和函数定义。因此变量top被定义了两次。
在头文件中只需声明变量
extern int top;主要的定义是
int top = -1;在函数之前,主标题之后。
请注意,在文件作用域中声明的变量具有存储类说明符extern和初始化器,表示变量的定义。您不能两次定义具有外部链接的变量。
来自C标准(6.9.2外部对象定义)
1如果对象的标识符声明具有文件范围和初始化程序,则声明是标识符的外部定义。
注意,一般来说,使用全局变量并不是一种好的方法。
发布于 2022-09-07 12:47:24
这些变量要么是stack.c的本地变量,要么是调用方的本地变量。不应在文件范围(任何函数之外)声明它们。通过声明extern,您可以声明“这是分配到其他地方的”。但是你从来没有把它分配到其他地方,这就是问题所在。另外,由于它是在其他地方分配的,所以初始化也必须放在其他地方。
然而,像这样使用extern是非常糟糕的做法,因为它创建了全局变量和意大利面代码,其中一个变量被跨多个文件共享,尽管它不应该共享。
相反,您可以将所有这些变量放置在结构中。对于初学者级的应用程序,只需这样做就足够了:
// stack.h
typedef struct
{
int stack_arr[MAX];
int top;
} stack;
void stack_init (stack* s);然后:
// stack.c
void stack_init (stack* s)
{
/* default initialization here */
s->top = -1;
}现在,代码的调用者可以包含stack.h,声明变量stack my_stack;,然后像stack_init(&my_stack);一样调用函数。
对于专业应用程序来说,上面的内容可能不够好,因为它违反了最好的设计实践,即私有封装。调用者可以访问结构的内部变量,尽管它们不应该。
https://stackoverflow.com/questions/73635613
复制相似问题