標籤:des style blog color io ar strong for div
第二十一題
What is the potential problem with the following C program? #include <stdio.h> int main() { char str[80]; printf("Enter the string:"); scanf("%s",str); printf("You entered:%s\n",str); return 0; }
題目講解:
易造成數組越界,scanf改成如下形式比較保險
scanf("%79s",str);
不管輸入多少個位元組,最多隻讀取79個位元組。
第二十二題
What is the output of the following program? #include <stdio.h> int main() { int i; i = 10; printf("i : %d\n",i); printf("sizeof(i++) is: %d\n",sizeof(i++)); printf("i : %d\n",i); return 0; }
題目講解:
輸出為:
i: 10
sizeof(i++) is:4
i: 10
sizeof(i++),等效於sizeof(int)。sizeof的值在編譯時間決定,不會執行i++。
sizeof的更多講解見第一題。
第二十三題
Why does the following program give a warning? (Please remember that sending a normal pointer to a function requiring const pointer does not give any warning) #include <stdio.h> void foo(const char **p) { } int main(int argc, char **argv) { foo(argv); return 0; }
題目講解
用const修飾變數,指定該變數為唯讀。const int a = 10;//變數a唯讀const int *p;//p指向的int型數唯讀,p可以被修改int *const p;//p為唯讀,p指向的int型數可以被修改
int a = 10;const int *p;p = &a;//一級const指標賦值時,可以不將右邊的指標轉換為const型
int *p;const int **pp;pp = (const int **)&p;//二級const指標賦值時,必須將右側二級指標轉換為const型
void foo(const char *p) {}int main(){char *p;foo(p);//p不用轉化為const型return 0;}
void foo(const char **pp) {}int main(){char **pp;foo((const char **)pp);//pp必須轉化為const型return 0;}
第二十四題
What is the output of the following program? #include <stdio.h> int main() { int i; i = 1,2,3; printf("i:%d\n",i); return 0; }
題目講解:
同第十題。
輸出: i:1
逗號運算子在所有的運算子中優先順序最低,i = 1,2,3等效於(i = 1),2,3
若將”i = 1,2,3”改成”i = (1,2,3)”,i的值為3。
第二十五題(Reverse Polish Notation)
The following is a piece of code which implements the reverse Polish Calculator. There is a(are) serious(s) bug in the code. Find it(them) out!!! Assume that the function getop returns the appropriate return values for operands, opcodes, EOF etc.. #include <stdio.h> #include <stdlib.h> #define MAX 80 #define NUMBER ‘0‘ int getop(char[]); void push(double); double pop(void); int main() { int type; char s[MAX]; while((type = getop(s)) != EOF) { switch(type) { case NUMBER: push(atof(s)); break; case ‘+‘: push(pop() + pop()); break; case ‘*‘: push(pop() * pop()); break; case ‘-‘: push(pop() - pop()); break; case ‘/‘: push(pop() / pop()); break; /* ... * ... * ... */ } } }
題目講解:(不確定)
減法的減數和被減數反了,除法的除數和被除數反了。
C puzzles詳解【21-25題】