c 语言杂记

在这笔记里面,记录着一些c语言平常的疑问,用来让自己可以快速记住一些特殊的地方

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.
下面举例几个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对字符串数组排序

qsort用来对字符串数组排序需要注意的地方,我们先看一下qsort的函数

void qsort(void *base, size_t nmemb, size_t size,int (*compar)(const void *, const void *));
分别说一下这个参数的意思

  • base: 字符串数组的的首地址
  • nmem: 数组元素的个数,这里其实就是字符串的个数
  • size: 每个元素的大小,这里每个元素都是指针变量,因此大小并不是字符串的小心,而是指针变量的大小,即sizeof(char *)
  • int (*compar)(const void*,const void*): 这里需要传入一个比较函数,下面说一下这个函数要注意的地方

找个例子来试试

#include 
#include 
#include 

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

你可能感兴趣的:(c 语言杂记)