对ctap中p52到p57的例子的思考
2015-05-21
ctap代表C Traps and Pitfalls这本书. 我觉得这本书中p52给出的例子有两个错误:
- row不该申明为局部变量,而应该申明为全局变量.
- 在flush函数中的一个for循环里row不应初始化为0.
下面给出这个例子的代码,这个例子打印输出1->42的数字,每页最多输出五行三列.
Code
#include <stdio.h>
#define NROWS 5
#define NCOLS 3
#define BUFSIZE (NROWS * (NCOLS - 1))
static int buffer[BUFSIZE];
static int row = 0;
int *bufptr = buffer;
void print(int n);
void printnum(int num);
void printnl();
void printpage();
void flush();
int main()
{
int i;
for(i = 0; i < 42; i++)
print(i);
flush();
return 0;
}
void print(int n){
if(bufptr == &buffer[BUFSIZE}) {
int *p;
for(p = buffer + row; p < bufptr; p += NROWS)
printnum(*p);
printnum(n);
printnl();
if(++row == NROWS) {
row = 0;
bufptr = buffer;
printpage();
}
}else {
*bufptr++ = n;
}
}
void printnum(int num) {
printf("%d\t", n);
}
void printnl() {
printf("\n");
}
void printpage() {
printf("------------------");
printnl();
}
void flush() {
int k = bufptr - buffer;
if (k > NROWS)
k = NROWS;
if (k > 0) {
for (; row < k; row++) {
int *p;
for (p = buffer + row; p < bufptr; p += NROWS)
printnum(*p);
printnl();
}
printpage();
}
}
comments powered by Disqus