前言:函數
C語言中有不少東西容易搞混,最近筆者就遇到了一個問題。這裏作個記錄。就是memcmp和strcmp二者的用法,這裏作個對比:spa
功能對比:code
A memcmp:blog
函數原型: int memcmp(const void *str1, const void *str2, size_t n));內存
功能:比較內存區域buf1和buf2的前count個字節。字符串
返回值:原型
B strcmp函數 源碼
函數原型:int
strcmp
(
const
char
*s1,
const
char
*s2);
string
功能:用於比較兩個字符串並根據比較結果返回整數io
返回值:
源碼對比:
下面這個例子,可以很好的詮釋兩個函數的用法:
1 #include <stdio.h> 2 #include <string.h> 3 4 5 int main() 6 { 7 unsigned char test1_arr[32] = "hello world"; 8 unsigned char test2_arr[32] = "hello world"; 9 10 int ret = memcmp(test1_arr,test2_arr,strlen(test1_arr)); 11 printf("unsigned char memcmp is:%d \n\t ",ret); 12 13 char test3_arr[32] = "hello world"; 14 char test4_arr[32] = "hello world"; 15 16 int reta = strcmp(test3_arr,test4_arr); 17 printf("char strcmp is:%d \n\t ",reta); 18 19 unsigned char test5_arr[32] = "hello world"; 20 unsigned char test6_arr[32] = "hello world"; 21 22 int retb = strcmp(test5_arr,test6_arr); 23 printf("char strcmp is:%d \n\t ",retb); 24 25 return 0; 26 }