美文网首页
c 语言杂记

c 语言杂记

作者: raingolee | 来源:发表于2016-04-10 13:53 被阅读21次

在这笔记里面,记录着一些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 <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]);
}

相关文章

  • c 语言杂记

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

  • C语言学习杂记(1)—语言畅想

    当婴儿呱呱坠地,一个生命就开始了他的征尘。环境与兴趣、学习与传授、成长与贡献,每一个名词都是围绕着语言而展开。语言...

  • C语言学习杂记(2)—C的数据

    计算机的计算和存储都是数据。在C语言里,数据同样是基础,学好数据的知识是必须的。先看一个最简单的例子 C中的基本数...

  • SwiftUI 官方教程|开发资料

    代码仓库:appke/PlaySwiftUI: SwiftUI官方文档,开发杂记[https://github.c...

  • C++简答题

    一、简答题 1、C语言与C++语言的区别? 答: C语言是面向过程语言,C++是面向对象语言(OOP) C语言...

  • C语言快速入门 - Hello World 详解

    目录 C语言快速入门 C语言快速入门 - Hello World 详解 C语言快速入门 - 变量 C语言快速入门 ...

  • C语言快速入门 - 简单运算符

    目录 C语言快速入门 C语言快速入门 - Hello World 详解 C语言快速入门 - 变量 C语言快速入门 ...

  • C语言快速入门 - 控制语句

    目录 C语言快速入门 C语言快速入门 - Hello World 详解 C语言快速入门 - 变量 C语言快速入门 ...

  • C语言快速入门 - 变量

    目录 C语言快速入门 C语言快速入门 - Hello World 详解 C语言快速入门 - 变量 C语言快速入门 ...

  • C语言快速入门

    目录 C语言快速入门 C语言快速入门 - Hello World 详解 C语言快速入门 - 变量 C语言快速入门 ...

网友评论

      本文标题:c 语言杂记

      本文链接:https://www.haomeiwen.com/subject/vsbblttx.html