#include
#include
#include
#define QueueSize 100//(100可变)
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node* next;
}Node;
Node* top;
typedef struct
{
DataType data[QueueSize];
int front, rear;
}CirQueue;
void Push(Node* top, DataType x)
{
Node* s = (Node*)malloc(sizeof(Node));
s->data = x;
s->next = top;
top = s;
}
int Pop(Node* top, DataType* ptr)
{
if (top == NULL)
{
printf("下溢错误,出栈失败\n");
return 0;
}
Node* p = top;
*ptr = p->data;
top = p->next;
free(p);
return 1;
}
void PrintL(Node* L)
{
Node* p = L;
if (p== NULL) printf("已空,打印失败\n");
else
{
while (p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
}
void InitQueue(CirQueue* Q)
{
Q->front = -1;
Q->rear = Q->front;
}
int EnQueue(CirQueue* Q, DataType x)
{
if ((Q->rear + 1) % QueueSize == Q->front)
{
printf("队列已满,入队失败\n");
return 0;
}
Q->rear = (Q->rear + 1) % QueueSize;
Q->data[Q->rear] = x;
return 1;
}
int DeQueue(CirQueue* Q, DataType* ptr)
{
if (Q->rear == Q->front)
{
printf("队列为空,出队失败\n");
return 0;
}
Q->front = ((Q->front + 1) % QueueSize);
*ptr = Q->data[Q->front];
return 1;
}
int main()
{
Node* L = (Node*)malloc(sizeof(Node));
top = L;
Push(top, 1);
PrintL(L);
}
请问一下,为什么输出会报错,说读取访问权限冲突,如何修改呢
void Push(Node* top, DataType x)
{
Node* s = (Node*)malloc(sizeof(Node));
s->data = x;
s->next = top->next;
top->next = s;
}
** 对push函数,此处猜测,想的应该是将top变为s,然后改变top
但是:top作为push的参数,是临时变量,是退出函数就会销毁,无法带出值。虽然定义过全局变量。但是,其因为在函数中有一个局部变量,编译器会先看函数中,那么他就是局部的,退出函数就会销毁,变为原来的全局变量时候的值。并未将值带出。
而且,如top将值带出,L也没有改变,还是原来的值。**
** printl函数中需要指针为空,但是没见到哪初始化指针为nullptr……(就按照前面面的成功,也容易死循环),按上代码:会读取访问权限冲突就是因为未将值带出,并且给L,所以next是随机值,即:读取访问权限冲突。**