一直以来困惑的问题,包括栈,队列,凡是用过结构体指针的实现,,
都存在问题,只是一直没有发现本质的错误,
就是定义了一个结构体指针还要,为其申请一个内存;
typedef struct stack
{
int top;
int base;
char *elem;
} stack, *stack1;
stack1
creat_stack(void)
{
stack1 s;
s = (stack1) malloc (sizeof(stack));
s->elem = (char*) malloc (maxsize * sizeof(char));
s->top = s->base = 0;
//printf("s->elem == %p
", s->elem);
return s;
}
定义了一个结构体 stack1 s; 还不可以对其进行操作,否则就会产生错误!!!
还需malloc like this
s = (stack1) malloc (stack);
定义的结构体指针只是说明这个指针是指向这个结构的,但并未给它分配内存空间,这就类似于声明,只是告诉系统我这个指针是干什么用的。
链表是由一个个的结点链接起来的,而每个结点都是需要内存空间来存储数据的,
所以你每新建一个结点,都需要开辟一个空间来存储数据.
错误举例
#include <cstdio>
#include <cstdlib>
//#define _OJ_
#define maxsize 5
typedef struct Lnode
{
int front;
int rear;
int *elem;
} deque, *Deque;
void
creat_deque(Deque q)
{
q->elem = (int*) malloc (maxsize * sizeof(int));
q->front = q->rear = 0;
}
int
isfull(Deque q)
{
if((q->rear + 1) % maxsize == q->front)
return 1;
else
return 0;
}
int
isempty(Deque q)
{
if(q->front == q->rear)
return 1;
else
return 0;
}
int
deque_size(Deque q)
{
return (q->front - q->rear + maxsize) % maxsize;
}
void
endeque(Deque q)
{
int x;
scanf("%d", &x);
q->elem[q->rear] = x;printf("%d ", q->rear);
q->rear = (q->rear + 1) % maxsize;
}
int
del_deque(Deque q)
{
int e;
e = q->elem[q->front];
q->front = (q->front + 1) % maxsize;
return e;
}
int main(int argc, char const *argv[]) {
#ifndef _OJ_ //ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
Deque q;//此处未给q分配内存空间!
creat_deque(q);
printf("isempty == %d ", isempty(q));
printf("size == %d ", deque_size(q));
printf("full == %d ", isfull(q));
int n, i;
n = 3;
do
{
endeque(q);
}
while (!isfull(q)) ;
while (!isempty(q)) {
printf("del == %d ", del_deque(q));
}
return 0;
}