[cpp] #include<stdio.h> #include<assert.h> #define N 100 char *my_strcpy(char *dest,char *src) { //返回值保存 char *p = dest; //檢查入參,使程序健壯 assert(dest != NULL || src !=NULL); //注意越界 while((*dest++ = *src++) != '\0'); //返回字符指針,是函數可以用於鏈式表達式,增強可用性 return p; } int main() { char str1[N]; char *str2 = "My future is wonderful."; printf("%s\n",my_strcpy(str1,str2)); return 0; } 進項目筆試中碰到的一個題目,求優化。 [cpp #include<stdio.h> #include<assert.h> #define N 100 /* 實現查找一個數組小於平均值的所有元素 number為要查找的數組,n元素個數,store返回的數組, 函數返回小於平均值的個數 */ int iFindSmallerNum(int number[],int n,int store[]) { int i,j=0,sum = 0,ave; *store = *store; assert(n>0); for(i=0; i<n; i++) sum += number[i]; ave = sum / n; for(i=0;i<n;i++) { if(number[i]<ave) store[j++] = number[i]; } return j; } int main() { int number[10] = {10,12,14,16,18,20,22,24,26,28}; int store[N]; int n,no = iFindSmallerNum(number,10,store); printf("%d\n",no); for(n = 0; n<no;n++) printf("%d\t",store[n]); return 0; }