这里是两个C程序来实现以简单的形式队列数据结构单个队列和多个队列使用同一程序不能工作
第一:
限定一个队列,它的工作完全
第二个:
定义了多个队列,它在执行时崩溃
功能都在这两个程序除了main()
是实施 同样是不同的一点。
所以这里的问题:为什么第二个代码不工作?
*这里是代码*
代码1:
/*
Single queue -- this work perfectly
*/
#include <stdio.h>
#define Q_MAX_SIZE 255
struct queue {
int* pointer;
int* currentValue;
int max, count, theQueue[Q_MAX_SIZE];
};
//prototyps
void initQueue(struct queue*);
unsigned short pushQueue(struct queue*, int);
int* popQueue(struct queue*);
int main(void) {
int j;
struct queue q;
initQueue(&q);
for (j = 0; j < 6; j++)
pushQueue(&q, j);
int* inputobj = popQueue(&q);
while (inputobj != NULL)
{
printf("%d ", *inputobj);
inputobj = popQueue(&q);
}
printf("\n\ndone..Queue is empty\n");
return 0;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void initQueue(struct queue *Q)
{
Q->pointer = Q->theQueue;
Q->max = Q_MAX_SIZE;
Q->count = 0;
}
unsigned short pushQueue(struct queue *Q, int input) {
if (Q->count < Q->max)
{
*Q->pointer = input;
Q->pointer++;
Q->count++;
return 1;
}
else
return 0;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
int* popQueue(struct queue *Q) {
int i;
if (Q->count > 0)
{
*Q->currentValue = *Q->theQueue;
Q->pointer--;
Q->count--;
for (i = 0; i < Q->count; i++)
{
int* currentPtr = Q->theQueue + i;
int* nextPtr = currentPtr + 1;
*currentPtr = *nextPtr;
}
return Q->currentValue;
}
else
NULL;
}
代码2:
/*
Multiple queues -- this not work and crash at execution
*/
#include <stdio.h>
#define Q_MAX_SIZE 255
struct queue {
int* pointer;
int* currentValue;
int max, count, theQueue[Q_MAX_SIZE];
};
//prototyps
void initQueue(struct queue*);
unsigned short pushQueue(struct queue*, int);
int* popQueue(struct queue*);
int main(void) {
int i, j;
struct queue obj[5];
for(i=0; i<5; i++)
{
initQueue(&obj[i]);
for(j = 0; j<3; j++)
{
pushQueue(&obj[i], j);
}
}
for(i=0; i<5; i++)
{
printf("Queue[%d]:\n", i);
int* inputobj;
inputobj = popQueue(&obj[i]);
while(inputobj != NULL)
{
printf("Queue[No.%d] = %d\n", i, *inputobj);
inputobj = popQueue(&obj[i]);
}
putchar('\n');
}
return 0;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void initQueue(struct queue *Q)
{
Q->pointer = Q->theQueue;
Q->max = Q_MAX_SIZE;
Q->count = 0;
}
unsigned short pushQueue(struct queue *Q, int input) {
if (Q->count < Q->max)
{
*Q->pointer = input;
Q->pointer++;
Q->count++;
return 1;
}
else
return 0;
}
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
int* popQueue(struct queue *Q) {
int i;
if (Q->count > 0)
{
*Q->currentValue = *Q->theQueue;
Q->pointer--;
Q->count--;
for (i = 0; i < Q->count; i++)
{
int* currentPtr = Q->theQueue + i;
int* nextPtr = currentPtr + 1;
*currentPtr = *nextPtr;
}
return Q->currentValue;
}
else
NULL;
}
更新:问题是initQueue()
和它的通过为Q->currentValue
分配内存 解决这里是编辑后的功能:
void initQueue(struct queue *Q)
{
Q->currentValue = malloc(sizeof(int));
Q->pointer = Q->theQueue;
Q->max = Q_MAX_SIZE;
Q->count = 0;
}
学习如何使用debbuger,看看发生了什么事情 –
我的猜测是,你要访问这样的:initQueue(&(OBJ [1])); – Jiminion
@Jim我做了你说的,但它不是工作 –