第三十四题
The following is a piece of C code, whose intention was to print a minus sign 20 times. But you can notice that, it doesn't work. #include <stdio.h> int main() { int i; int n = 20; for( i = 0; i < n; i-- ) printf("-"); return 0; } 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 = 0; i < n; i-- )
改成
for( i = 0; 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 = 10; return 0; }
题目讲解:
int* ptr1,ptr2;
ptr1是指针,ptr2不是指针
改成
int *ptr1,*ptr2;
第三十六题
What is the output of the following program? #include <stdio.h> int main() { int cnt = 5, a; do { a /= cnt; } while (cnt --); printf ("%d ", a); return 0; }
题目讲解:
cnt减到最后为0,运行后有“trap divide error”“floating point exception”的错误。
第三十七题
What is the output of the following program? #include <stdio.h> int main() { int i = 6; if( ((++i < 7) && ( i++/6)) || (++i <= 9)) ; printf("%d ",i); return 0; }
题目解答:
i的值为8。先执行(++i < 7),此表达式的值为0,i=7,由于逻辑运算符的短路处理,(i++/6)跳过执行,
((++i < 7) && ( i++/6))值为0,接着执行(++i <= 9),i的值最终为8。