C 在多个文件中放置代码的堆栈实现
我试图通过在单独的源文件中写入堆栈的所有函数来实现堆栈。但是,我收到很多错误,说指针类型不兼容。当我将函数包含在主C文件中时,这些错误不会出现。这些是我的文件。我对此不熟悉。请帮助我更正它们。 非常感谢。 我的主要代码是C 在多个文件中放置代码的堆栈实现,c,C,我试图通过在单独的源文件中写入堆栈的所有函数来实现堆栈。但是,我收到很多错误,说指针类型不兼容。当我将函数包含在主C文件中时,这些错误不会出现。这些是我的文件。我对此不熟悉。请帮助我更正它们。 非常感谢。 我的主要代码是 #include "myfunctions.h" int main() { int operation,data; struct stack *One = (struct stack *)malloc(sizeof(struct stack)); One
#include "myfunctions.h"
int main()
{
int operation,data;
struct stack *One = (struct stack *)malloc(sizeof(struct stack));
One->top = -1;
printf("stack functionality \n");
while(1)
{
if (isEmpty(One))
{
printf("enter 1 to push \n");
scanf("%d",&operation);
}
else if (isFull(One))
{
printf("stack is full.enter 2 to pop or 3 to diplay \n");
scanf("%d",&operation);
}
else
{
printf("enter 1 to push,2 to pop,3 to display 4 to exit \n");
scanf("%d",&operation);
}
switch (operation)
{
case 1: printf("enter data to be pushed \n");
scanf("%d",&data);
push(One,data);
break;
case 2: printf("%d \n",pop(One));
break;
case 3: display(One);
break;
case 4:exit(0);
}
}
}
stackfns代码
#include <myfunctions.h>
bool isEmpty(struct stack *b)
{
if(b->top == -1) return true;
else return false;
}
bool isFull(struct stack *b)
{
if(b->top == 9) return true;
else return false;
}
void push(struct stack *b,int data)
{
b->a[++(b->top)] = data;
}
int pop(struct stack *b)
{
return (b->a[(b->top)--]);
}
void display(struct stack *b)
{
int i;
for (i=0;i<10;i++)
printf("%d ",b->a[i]);
printf("\n");
}
#包括
bool isEmpty(结构堆栈*b)
{
如果(b->top==-1)返回true;
否则返回false;
}
bool已满(结构堆栈*b)
{
如果(b->top==9)返回true;
否则返回false;
}
void push(结构堆栈*b,int数据)
{
b->a[++(b->top)]=数据;
}
int-pop(结构堆栈*b)
{
返回(b->a[(b->top)--];
}
无效显示(结构堆栈*b)
{
int i;
对于(i=0;ia[i]);
printf(“\n”);
}
头文件
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
extern bool isEmpty(struct stack *b);
extern bool isFull(struct stack *b);
extern void push(struct stack *b,int data);
extern int pop(struct stack *b);
extern void display(struct stack *b);
#define max_size 10
struct stack
{
int a[max_size];
int top;
};
#包括
#包括
#包括
外部布尔为空(结构堆栈*b);
外部布尔已满(结构堆栈*b);
外部无效推送(结构堆栈*b,内部数据);
外部int pop(结构堆栈*b);
外部无效显示(结构堆栈*b);
#定义最大尺寸10
结构堆栈
{
int a[最大尺寸];
int top;
};
在头文件中,您需要首先贴花结构:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define max_size 10
struct stack
{
int a[max_size];
int top;
};
extern bool isEmpty(struct stack *b);
extern bool isFull(struct stack *b);
extern void push(struct stack *b,int data);
extern int pop(struct stack *b);
extern void display(struct stack *b);
.c文件:
struct xx_t {
...
};
您是如何编译的?Gcc file1.c stackfns.c函数名始终通过prototype语句可见,因此不需要使用
extern
修饰符。注意:另一个文件中的数据确实需要外部修改器头文件缺少“多重包含”保护。应该增加这一保护。建议在头文件的开头使用:#ifndef FUNCTIONS#u H#define FUNCTIONS_H
,并在头文件的末尾使用:#endif//FUNCTIONS_H
注意:头文件只应是#包含实际需要的
d。在C中,我认为不需要在函数声明之前声明结构,但这绝对是个好主意。“旧版本的C语言没有原型,函数声明只指定了返回类型,没有列出参数类型。”我不理解你答案中隐藏部分的内部实现。你能解释一下吗,结构的内部表示确实需要“公开”,因为用户的调用函数需要一个指向定义的正确指针,因此可以设置、读取、更新数据等。如果函数已编写为“访问器”函数,则调用方不需要结构的实际定义
struct xx_t {
...
};