第三十四题
The following is a piece of C code, whose intention was to print a minus sign times. But you can notice that, it doesn't work.
#include <stdio.h>
int main()
{
int i;
int n = ;
for( i = ; i < n; i-- )
printf("-");
return ;
}
Well fixing the above code is straight-forward. To make the problem interesting, you have to fix the above code, by changing exactly one character. There are three known solutions. See if you can get all those three.
题目讲解:
将
for( i = ; i < n; i-- )
改成
for( i = ; i < n; n-- )
第三十五题
What's the mistake in the following code?
#include <stdio.h>
int main()
{
int* ptr1,ptr2;
ptr1 = malloc(sizeof(int));
ptr2 = ptr1;
*ptr2 = ;
return ;
}
题目讲解:
int* ptr1,ptr2;
ptr1是指针,ptr2不是指针
改成
int *ptr1,*ptr2;
第三十六题
What is the output of the following program?
#include <stdio.h>
int main()
{
int cnt = , a; do {
a /= cnt;
} while (cnt --); printf ("%d\n", a);
return ;
}
题目讲解:
cnt减到最后为0,运行后有“trap divide error”“floating point exception”的错误。
第三十七题
What is the output of the following program?
#include <stdio.h>
int main()
{
int i = ;
if( ((++i < ) && ( i++/)) || (++i <= ))
;
printf("%d\n",i);
return ;
}
题目解答:
i的值为8。先执行(++i < 7),此表达式的值为0,i=7,由于逻辑运算符的短路处理,(i++/6)跳过执行,
((++i < 7) && ( i++/6))值为0,接着执行(++i <= 9),i的值最终为8。