示例代码:
#include <stdio.h>
char Buff[12];
/* 获取数组大小 */
#define GET_BUFF_SIZE(Arry) (sizeof((Arry)) / sizeof(Arry[0]))
/* X自加时访问Arry数组,防止数组越界访问 */
#define INC_BUFF_NUM(Arry, X) {(X)++; (X) = (X) % GET_BUFF_SIZE((Arry));}
int main(void)
{
char i = 0;
char n = 0;
while(1)
{
Buff[i] = n;
printf("Buff[%d] = %d\n", i, Buff[i]);
INC_BUFF_NUM(Buff, i);
n++;
if(n == 20)
break;
}
return 0;
}
运行结果
Buff[0] = 0
Buff[1] = 1
Buff[2] = 2
Buff[3] = 3
Buff[4] = 4
Buff[5] = 5
Buff[6] = 6
Buff[7] = 7
Buff[8] = 8
Buff[9] = 9
Buff[10] = 10
Buff[11] = 11
Buff[0] = 12
Buff[1] = 13
Buff[2] = 14
Buff[3] = 15
Buff[4] = 16
Buff[5] = 17
Buff[6] = 18
Buff[7] = 19
通过打印可以看出 “i = i % BUFF_MAX;” 把数组的最大值限制在BUFF_MAX-1下,i++不会使数组越界。