c 語(yǔ)言雜記

在這筆記里面,記錄著一些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]);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容