【发布时间】:2017-04-03 23:06:10
【问题描述】:
在下面的函数中。我尝试使用堆栈并使用数组实现。我制作了 create stack 、 push 、 pop 等函数。但是在编译时显示错误。请帮我找出问题所在?
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
struct stack_struct {
char a[100];
int top;
};
typedef struct stack_struct *stack;
stack charc;
stack createstack() {
stack s = (stack) malloc(sizeof(struct stack_struct));
s->top = -1;//initialize the stack
return s;
}
void push(stack s, char x) {
s->top++;
s->a[s->top] = x;
}
char pop(stack s) {
assert(s->top > 0);
char x;
x = s->a[s->top];
s->top--;
return x;
}
void printstack(stack s) {
while (s->top != -1) {
printf("%c", s->a[s->top]);
s-> top--;
}
void main() {
charc = createstack();
push(charc, 3);
printstack(charc);
pop(charc);
printstack(charc);
push(charc, 4);
printstack(charc);
push(charc, 5);
printstack(charc);
push(charc, 6);
printstack(charc);
push(charc, 7);
printstack(charc);
}
}
【问题讨论】:
-
错误和行号是什么?
-
可能不相关,但你不应该投
malloc -
用
typedef隐藏指针容易出错,被认为是不好的做法,使代码更难阅读......