# C語言誤區 ## 副函式內用Sizeof找input array大小錯誤!? ==結論:此函式內宣告的array可以用sizeof(array)/sizeof(*array)來找大小== ==但是作為函式input的array address是作為指標陣列,sizeof會出錯== ```c= #include <stdio.h> void pt(int a[]){ printf("sizeof(a)=%d\tsizeof(*a)=%d\n",sizeof(a),sizeof(*a)); //sizeof(a)=8 sizeof(*a)=4 return; } void pt2(int *a){ printf("sizeof(a)=%d\tsizeof(*a)=%d\n",sizeof(a),sizeof(*a)); //sizeof(a)=8 sizeof(*a)=4 return; } int main(void) { int a[5]={0}; printf("sizeof(a)=%d\tsizeof(*a)=%d\n",sizeof(a),sizeof(*a)); //sizeof(a)=20 sizeof(*a)=4 pt(a); pt2(a); return (0); } ``` main的printf時,a作為array存放5格int變數,故大小為5*4=20(int 4 Bytes),而*a相當於a[0],大小為int 4 Bytes pt的printf時,此時a雖然input是給int a[],但實際上是相當於int* a,指向int的指標,sizeof(a)相當於sizeof(int*),指標的大小由電腦位元系統決定,32位元為4,我是64位元則為8,而*a一樣相當於a[0],大小為int 4 Bytes pt2的printf時,同前者。 ## strcmp與strncmp結果不同!? ==結論:先看比較對象字尾有沒有加上\0== ```c #include<stdio.h> #include<stdlib.h> #include<string.h> int main(){ char* mumi=(char *)malloc(sizeof(char)); if(!mumi){ printf("Failed to allocate memory\n"); free(mumi); return 0; } *mumi='M'; int str,strn; str=strcmp(mumi,"M"); strn=strncmp(mumi,"M",1); printf("strcmp=%d\n",str); printf("strncmp=%d",strn); free(mumi); return 0; } ``` 跑完結果如下 ``` strcmp =1 strncmp=0 ``` mumi當中存有字元M,然而用strcmp及strncmp與"M"相比較為何結果不相同!? 回頭去翻C語言規格書查看一下定義 - **7.21.4.2 The strcmp function** - **Synopsis** ```c #include <string.h> int strcmp(const char *s1, const char *s2); ``` - **Description** > The strcmp function compares the string pointed to by s1 to the string pointed to by s2. - **Returns** >The strcmp function returns an integer greater than, equal to, or less than zero,accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2. 然而其比較的終止條件是比到錯誤or遇到\0,所以不像strncmp指定只比第一個bit就結束,結尾上同樣得加上\0終止字符。 ```c #include<stdio.h> #include<stdlib.h> #include<string.h> int main(){ char* mumi=(char*)malloc(2*sizeof(char)); if(!mumi){ printf("Failed to allocate memory\n"); free(mumi); return 0; } *mumi='M'; *(mumi+1)='\0'; //增加\0 int str,strn; str=strcmp(mumi,"M"); strn=strncmp(mumi,"M",1); printf("strcmp=%d\n",str); printf("strncmp=%d",strn); free(mumi); return 0; } ``` 執行結果 ``` strcmp =0 strncmp=0 ``` ## 資料計算型態(Overflow注意!!)