【发布时间】:2020-03-05 15:40:14
【问题描述】:
我正在尝试使用固定长度数组来实现堆栈。我想创建多个 Stack 实例,所以我的 stack 实现在我的 stack.h 标头中。
stack.h
#ifndef STACK_H
#define STACK_H
typedef int Item;
typedef struct stack{
Item array[SIZE];
int current_size;
}Stack;
Stack *create_stack(void);
void push_stack(Stack *stack, Item value);
Item pop_stack(Stack *stack);
#endif
但是,我想保持数组的大小私有,所以我在 stack.c 中定义了它
stack.c
#include "stack.h"
#define SIZE 100
Stack *create_stack(void)
{
....
}
void push_stack(Stack *stack, Item value)
{
....
}
Item pop_stack(Stack *stack)
{
....
}
这可能吗?是否在源文件中定义了宏但在头文件中使用? 谢谢
【问题讨论】:
-
嗯,也许是一个灵活的数组成员?
typedef struct stack{ int current_size; Item array[]; }Stack;,但为什么不直接使用typedef struct stack{ int current_size; Item *array; }Stack;呢? Jules,你为什么要在Stack中创建一个未知公共大小的array?答案可以导致更好的方法。 -
作业规定栈必须使用定长数组。
-
Jules,你想要的是opaque pointer,永远不要向公众展示
typedef struct stack{ Item array[SIZE]; int current_size; }Stack;。让所有对Stack的访问都通过Stack*和函数进行。
标签: c arrays header stack include