在這筆記里面,記錄著一些c語(yǔ)言平常的疑問(wèn),用來(lái)讓自己可以快速記住一些特殊的地方
Why use strcmp instead of == in C
strcmp compares the actual C-string content, while using == between two C-string is asking if this two char pointers point to the same position.
下面舉例幾個(gè)C-sting的例子
char string_a[] = "foo";
char string_b[] = "foo";
char * string_c = string_a;
strcmp(string_a, string_b) == 0 would return true, while string_a == string_b would return false. Only when "comparing" string_a and string_c using == would return true.
If you want to compare the actual contents of two C-string but not whether they are just alias of each other, use strcmp.
用qsort對(duì)字符串?dāng)?shù)組排序
qsort用來(lái)對(duì)字符串?dāng)?shù)組排序需要注意的地方,我們先看一下qsort的函數(shù)
void qsort(void *base, size_t nmemb, size_t size,int (*compar)(const void *, const void *));
分別說(shuō)一下這個(gè)參數(shù)的意思
- base: 字符串?dāng)?shù)組的的首地址
- nmem: 數(shù)組元素的個(gè)數(shù),這里其實(shí)就是字符串的個(gè)數(shù)
- size: 每個(gè)元素的大小,這里每個(gè)元素都是指針變量,因此大小并不是字符串的小心,而是指針變量的大小,即sizeof(char *)
- int (*compar)(const void*,const void*): 這里需要傳入一個(gè)比較函數(shù),下面說(shuō)一下這個(gè)函數(shù)要注意的地方
找個(gè)例子來(lái)試試
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int myCompare (const void * a, const void * b ) {
const char *pa = *(const char**)a;
const char *pb = *(const char**)b;
return strcmp(pa,pb);
}
int main() {
int i;
const char *input[] = {"a","orange","apple","mobile","car"};
int stringLen = sizeof(input) / sizeof(char *);
qsort(input, stringLen, sizeof(char *), myCompare);
for (i=0; i<stringLen; ++i)
printf("%d: %s\n", i, input[i]);
}