开发者

Pointers to structures

开发者 https://www.devze.com 2022-12-31 22:03 出处:网络
typedef struct queue { int q[max]; int qhead; int qrear; } queue; void init_queue(queue *QUEUE) { QUEUE.qhead = 0;
typedef struct queue {

  int q[max];
  int qhead;
  int qrear;

} queue;


void init_queue(queue *QUEUE)
{
  QUEUE.qhead = 0;
  QUEUE.qrear = -1;
}
void enqueue(queue *QUEUE,int data)
{
  QUEUE.qrear++;
  QUEUE.q[QUEUE.qrear] = data;
}

开发者_运维百科int process_queue(queue *QUEUE)
{
  if(QUEUE.qhead > QUEUE.qrear) 
    return -1;
  else
    return QUEUE.q[QUEUE.qhead++];
}

I am implementing queues using arrays just to keep it simple. Wats the error with the above code?


First of all, the . operator is used to access members of a struct. You need -> to access members of a pointer to a struct:

void init_queue(queue *QUEUE)
{
  QUEUE->qhead = 0;
  QUEUE->qrear = -1;
}

Just as a tid-bit, a->b is equivalent to (*a).b - that is, first dereferencing the pointer a, and then accessing a member of that struct.


Besides the compilation error from using . instead of ->, you also have potential buffer overflow in enqueue; you'll overflow your buffer after max calls. You have a couple of choice depending on what you want.

1) You can turn this into a circular queue:

void enqueue(queue *QUEUE,int data)
{
  QUEUE->qrear = (QUEUE->qrear + 1) % max;
  QUEUE->q[QUEUE->qrear] = data;
}

2) You can stop adding once you hit max:

void enqueue(queue *QUEUE,int data)
{
  if (QUEUE->qrear < (max - 1))
  {
    QUEUE->qrear++;
    QUEUE->q[QUEUE->qrear] = data;
  }
}


You should use -> instead of .:

Accessing structs' values using pointers is done using QUEUE-> or (*QUEUE). and not QUEUE.. You first need to dereference the pointer and only then access the value.

typedef struct queue {

  int q[max];
  int qhead;
  int qrear;

} queue;


void init_queue(queue *QUEUE)
{
  QUEUE->qhead = 0;
  QUEUE->qrear = -1;
}
void enqueue(queue *QUEUE,int data)
{
  QUEUE->qrear++;
  QUEUE->q[QUEUE->qrear] = data;
}

int process_queue(queue *QUEUE)
{
  if(QUEUE->qhead > QUEUE->qrear) 
    return -1;
  else
    return QUEUE->q[QUEUE->qhead++];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消