標籤:style blog color io os ar strong div sp
第十六題
The following is a small C program split across files. What do you expect the output to be, when both of them compiled together and run?File1.c int arr[80];File2.c extern int *arr; int main() { arr[1] = 100; return 0; }
題目講解:
編譯完運行發生段錯。
File1.c中聲明的是個數組,File2.c中聲明的是個指標,雖然名字一樣,但倆arr處於不同的記憶體位址,Flie2.c中的arr==NULL,對0地址操作是非法的。
將File2.c中的”extern int *arr;”改為”extern int arr[80];”就可以了。
第十七題
Explain the output of the following C program (No, the output is not 20). #include<stdio.h> int main() { int a=1; switch(a) { int b=20; case 1: printf("b is %d\n",b); break; default:printf("b is %d\n",b); break; } return 0; }
題目講解:
輸出:b is 0
switch判斷後直接跳轉到相應的case/default處,不會執行之前的指派陳述式。
第十八題
What is the output of the following program? (Again, it is not 40, (if the size of integer is 4)). #define SIZE 10 void size(int arr[SIZE]) { printf("size of array is:%d\n",sizeof(arr)); } int main() { int arr[SIZE]; size(arr); return 0; }
題目講解:
數組做參數傳遞時退化為指標,“void size(int arr[SIZE]) ”等價於“void size(int *arr) ”。size(arr)給size函數傳入的參數是指標,所以sizeof(arr)是指標的大小。
第十九題
The following is a simple c program, in which there is a function called Error to display errors. Can you see a potential problem with the way Error is defined? #include <stdlib.h> #include <stdio.h> void Error(char* s) { printf(s); return; } int main() { int *p; p = malloc(sizeof(int)); if(p == NULL) { Error("Could not allocate the memory\n"); Error("Quitting....\n"); exit(1); } else { /*some stuff to use p*/ } return 0; }
題目講解:
網上搜了下,沒有統一的解釋,說說個人的理解。
Google “void Error(char* s)”,發現如下幾種列印字串的方式:
方式1:void error(char *msg) { fprintf(stderr, msg);}方式2:void error(char *msg){ printf(msg); fflush(stdout);}方式3:void error(char *msg){puts(msg);}
根據第四題的解釋我們知道,stdout是行緩衝,只有遇到’\n’,緩衝區的內容才會列印出來,stderr是無緩衝,寫向stderr的內容
可以立馬列印出來。所以我推斷,題目中的Error函數的隱患是,若傳進去的字串不帶’\n’,該錯誤訊息就不會立馬列印出來,
直到遇到’\n’,或人為fflush(stdout),或緩衝區溢位,或進程退出才會把緩衝區內的錯誤訊息列印出來。
第二十題
What is the differnce between the following function calls to scanf?(Please notice the space carefully in the second call. Try removing it and observe the behaviour of the program) #include <stdio.h> int main() { char c; scanf("%c",&c); printf("%c\n",c); scanf(" %c",&c); printf("%c\n",c); return 0; }
題目講解:
當第二個scanf沒有空白符時,運行代碼,輸入a,斷行符號後,會列印a,換行,換行,然後程式結束,字元’a’被第一個scanf讀取,字元’\n’被第二個scanf讀取;
當第二個scanf有空白符時,運行代碼,輸入a,斷行符號,輸出a,若繼續敲斷行符號,程式不結束,直到輸入了字元(非分行符號)後,列印該字元,程式結束。
C99的7.19.6.2第五條說,包含空白符的指令讀取輸入中的第一個非空白字元。
A directive composed of white-space character(s) is executed by reading input up to
the ?rst non-white-space character (which remains unread), or until no more characters
can be read.
C puzzles詳解【16-20題】