Question

I'm trying to implement a queue in C using a linked list that stores void pointers. I'm having a problem with the insert function; front always equals rear after an insert (testing with ints). I'm having trouble pin-pointing the problem.

typedef struct node{
    void *data;
    struct node *next;
} Node;

typedef struct queueStruct{
    struct node *front, *rear;
} queueStruct;

typedef struct queueStruct *QueueADT;

QueueADT que_create( ){
    QueueADT queue;
    queue = (QueueADT) malloc(sizeof(queueStruct));
    if(queue != NULL){
        queue->front = queue->rear = NULL;
    }
    else{
        printf("Insufficient memory for new queue.\n");
        exit(1);
    }
    return queue;
}

void que_insert( QueueADT queue, void *data ){

    Node *newNode;
    newNode = malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    if(queue->front == NULL){
        queue->front = queue->rear = newNode;
    }
    else{
        queue->rear->next = newNode;
        queue->rear = newNode;
    }
    printf("%i\t%i\n",  *((int *) queue->front->data),  *((int *)queue->rear->data) );
}
int main(void){
    QueueADT test;
    test = que_create();
    for(int i=0; i<9; ++i) {
         que_insert(test, (void *) &i);
   }
}
Was it helpful?

Solution

Using:

int main(void)
{
  int a =1, b=2, c=3;
  struct queueStruct queue = {0};
  que_insert( &queue, &a);
  que_insert( &queue, &b);
  que_insert( &queue, &c);
}

I get:

> ./q
1       1
1       2
1       3

Seems that it works to me. Than again, you didn't post your driver code. If you are doing something like:

int main(void)
{
  int a=1;
  struct queueStruct queue = {0};
  que_insert( &queue, &a);
  a=2;
  que_insert( &queue, &a);
}

Then it will always be the same, because both nodes point to the same address in memory, so when you change a to 2, both node's pointers point to the same memory and therefore are changed at the same time. Most likely, this is your real problem.

OTHER TIPS

The problem is the data you're putting into the queue. You've got a local variable, i, and you provide &i for everything -- so all the elements in your queue are the same element (whose value changes as you run through your loop).

You need to make discrete objects to put in your queue!

for(int i=0; i<9; ++i) {
    int *object = malloc(sizeof(*object);
    *object = i;
    que_insert(test, (void *) object);
}

Doing this, you'll need to remember to free(...) your objects once you're done with them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top