c 语言杂记

2016-04-10  本文已影响21人  raingolee

在这笔记里面,记录着一些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 *));
分别说一下这个参数的意思

找个例子来试试

#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]);
}
上一篇 下一篇

猜你喜欢

热点阅读