为什么malloc无法正常分配内存
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef int QElemType;
typedef struct
{
QElemType *base;
int front;
int rear;
}SqQueue;
Status InitQueue(SqQueue *Q,int n)
{
Q->base= (QElemType *)malloc(n*sizeof(QElemType));
if(!Q->base) exit(OVERFLOW);
Q->front=Q->rear=0;
return OK;
}
//int QueueLength(SqQueue *Q)
//{
// return (Q->rear-Q->front+MAXSIZE)%MAXSIZE;
//}
Status EnQueue(SqQueue *Q,QElemType e,int n)
{
if((Q->rear+1)%n==Q->front) return ERROR;
Q->base[Q->rear]=e;
Q->rear=(Q->rear+1)%n;
return OK;
}
// Status Queue(SqQueue *Q){
// while
// }
void DeQueue(SqQueue *Q,QElemType *e,int n)
{
while(Q->base[Q->front]=0){
Q->front=(Q->front+1)%n;
}
*e=Q->base[Q->front];
Q->front=(Q->front+1)%n;
}
//Status GetHead(SqQueue *Q,QElemType *e)
//{
// if(Q->rear==Q->front) return ERROR;
// *e=Q->base[Q->front];
// return OK;
//}
void DestroyQueue(SqQueue *Q)
{
if(Q->base) free(Q->base);
Q->base=NULL;
Q->front=0;
Q->rear=0;
}
int main()
{
SqQueue *Q;
//自行编写代码
int n;
scanf("%d",&n);
int m;
scanf("%d",&m);
InitQueue(Q,n);
printf("+");
for (int i=1;i<=n;i++){
EnQueue(Q,i,n);
}
int e;
int k=n;
while(k!=1){
int f;
for(int j=0;j<m;j++){
DeQueue(Q,&f,n);
}
Q->base[Q->front]=0;
k--;
}
DeQueue(Q,&e,n);
printf("%d",e);
return 0;
}
两个问题
这里判断相等写错了
->
用于结构体指针,.
用于结构体变量&Q
如果对你有帮助,还请点个采纳,万分感谢!
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef int QElemType;
typedef struct SqQueue
{
QElemType* base;
int front;
int rear;
}SqQueue;
Status InitQueue(SqQueue* Q, int n)
{
Q->base = (QElemType*)malloc(n * sizeof(QElemType));
if (!Q->base) exit(OVERFLOW);
Q->front = Q->rear = 0;
return OK;
}
//int QueueLength(SqQueue *Q)
//{
// return (Q->rear-Q->front+MAXSIZE)%MAXSIZE;
//}
Status EnQueue(SqQueue* Q, QElemType e, int n)
{
if ((Q->rear + 1) % n == Q->front) return ERROR;
Q->base[Q->rear] = e;
Q->rear = (Q->rear + 1) % n;
return OK;
}
// Status Queue(SqQueue *Q){
// while
// }
void DeQueue(SqQueue* Q, QElemType* e, int n)
{
while (Q->base[Q->front] == 0) {
Q->front = (Q->front + 1) % n;
}
*e = Q->base[Q->front];
Q->front = (Q->front + 1) % n;
}
//Status GetHead(SqQueue *Q,QElemType *e)
//{
// if(Q->rear==Q->front) return ERROR;
// *e=Q->base[Q->front];
// return OK;
//}
void DestroyQueue(SqQueue* Q)
{
if (Q->base) free(Q->base);
Q->base = NULL;
Q->front = 0;
Q->rear = 0;
}
int main()
{
SqQueue Q;
//自行编写代码
int n;
scanf("%d", &n);
int m;
scanf("%d", &m);
InitQueue(&Q, n);
printf("+");
for (int i = 1; i <= n; i++) {
EnQueue(&Q, i, n);
}
int e;
int k = n;
while (k != 1) {
int f;
for (int j = 0; j < m; j++) {
DeQueue(&Q, &f, n);
}
Q.base[Q.front] = 0;
k--;
}
DeQueue(&Q, &e, n);
printf("%d", e);
return 0;
}