C语言之对队列、结构体、指针、数组的理解
附测试例子
#include <stdio.h>
#include <assert.h>
#define QueueSize 100
typedef unsigned char datatype;
//队列的数据元素
typedef struct {
int front;
int rear;
int count; //用于计数
datatype data[QueueSize]; //用于缓存数组
}cirqueue;
cirqueue QUEUE;
//置空队
void InitQueue(cirqueue *q)
{
q->front = q->rear = 0;
q->count = 0;
}
//判断队满
int QueueFull(cirqueue *q)
{
return (q->count == QueueSize);
}
//判断队空
int QueueEmpty(cirqueue *q)
{
return (q->count==0);
}
//入队
void EnQueue(cirqueue *q,datatype x)
{
assert(QueueFull(q) == 0);//q满 终止程序
q->count++;
q->data[q->rear] = x;
q->rear = (q->rear + 1)%QueueSize;//循环队列设计 防止内存浪费
}
//出队
datatype DeQueue(cirqueue *q)
{
datatype temp;
assert(QueueEmpty(q)==0); //q空,则终止程序,打印错误信息
temp=q->data[q->front];
q->count--;
q->front = (q->front +1)%QueueSize;
return temp;
}
void main()
{
datatype aa[8]={0x12,0x33,0x88,0};
datatype dat[8]={0};
datatype byte1,byte2,byte3,byte4;
datatype *point,*point2=aa;
int a=0x12345678;
int b=0;
EnQueue(&QUEUE,aa[0]);
EnQueue(&QUEUE,aa[1]);
EnQueue(&QUEUE,aa[2]);
EnQueue(&QUEUE,aa[3]);
//assert( 表达式 ); //若表达式为假(为0),则向stderr 打印一条出错信息,然后调用abort来终止程序
//assert主要用于调试程序
printf("0x%x\n",QUEUE.count);
dat[0] = DeQueue(&QUEUE);
dat[1] = DeQueue(&QUEUE);
dat[2] = DeQueue(&QUEUE);
dat[3] = DeQueue(&QUEUE);
printf("0x%x\n",dat[0]);
printf("0x%x\n",dat[1]);
printf("0x%x\n",dat[2]);
printf("0x%x\n",dat[3]);
/*测试32位数据的拆分*/
byte1=a&0xff;
byte2=(a>>8)&0xff;
byte3=(a>>16)&0xff;
byte4=(a>>24)&0xff;
printf("0x%x\n",byte1);
printf("0x%x\n",byte2);
printf("0x%x\n",byte3);
printf("0x%x\n",byte4);
/*测试32位数据的合并*/
b = byte1 | (byte2<<8) | (byte3<<16) | (byte4<<24);
printf("0x%x\n",b);
printf("%d\n",b);
/*用于测试指针与数组的关系*/
point = aa;// 此时 point 和 aa 是同一地址
printf("0x%x\n",*point);
printf("0x%x\n",*(point+1));
printf("0x%x\n",*(point+2));
printf("0x%x\n",*(point+3));
printf("0x%x\n",&aa);
printf("0x%x\n",&(*point));
printf("0x%x\n",&a);
printf("0x%x\n",&b);
//
printf("0x%x\n",*point2);
printf("0x%x\n",*(point2+1));
for(;;)
{
}
}