首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QSort索引字符**

QSort索引字符**
EN

Stack Overflow用户
提问于 2016-03-17 15:27:08
回答 1查看 105关注 0票数 0

我得整理一下:

第一章**路

它包含如下一行:

807

每行在开头有一个数字,我需要用它对它们进行排序

但我不知道如何使用strtol是快速排序cmp_fct

代码示例:

代码语言:javascript
复制
    char ** lu = NULL;
    int nlu = 0;
    size_t n_byte = 10000*8; // 10000 octects par ligne cf:énoncé

    void lire(FILE * from){ //rm data.out && ./a.out < data.in > data.out && cmp -b data.in data.out

      char* ligne = malloc(n_byte);
      lu = malloc(n_byte);
      assert(lu != NULL);
      assert(ligne != NULL);


      while(getline(&ligne, &n_byte, from) != -1) // getline return -1 on failure to read a line (including end-of-file condition)
      {
        if (ligne[strlen(ligne) - 1] != '\n')
          fprintf(stderr, "Aie ! Ligne trop longue (%d max)\n", MaxCar);

        else
          ligne[strlen(ligne) - 1] = '\0';

        if (nlu == MaxLig)
        {
          fprintf(stderr, "Aie ! Trop de lignes (%d max)\n", MaxLig);
          break;
        }

        lu[nlu] = malloc(n_byte);
        assert(lu != NULL);
        assert(lu[nlu] != NULL);
        memcpy(lu[nlu], ligne, n_byte); /* /?\ + standard que strdup /?\*/

        if (lu[nlu] == NULL){
          fprintf(stderr, "Aie ! Plus de mémoire\n");
          exit(1);
        }
        nlu += 1;
      }
    }

    static int int_cmp(const void *a, const void *b) 
{ 
   const long ia = strtol(a, NULL, 10); // casting pointer types 
   const long ib = strtol(b, NULL, 10); // casting pointer types 
   printf("\n ia =%ld", ia);
   printf("\n ib =%ld", ib);
   if(ia < ib)
        return -1;
   return ia > ib;
} 

    void
    ecrire(FILE * to){
      int i;

      for(i = 0; i < nlu; i++)
        printf("%s\n", lu[i]);
    }

    int
    main(int ac, char * av[]){
      lire(stdin);
      qsort(lu, nlu, sizeof(lu[0]), int_cmp);
      ecrire(stdout);
      return 0;
    }

我如何使用快速排序:

代码语言:javascript
复制
qsort(lu, nlu, sizeof(lu[0]), int_cmp);

nlu是要排序的行数。

我想我必须在 strtol ()中使用b,但是strtol显示了错误的索引(0或1)。

strtol()的原型: long int strtol(const char *str, char **endptr, int base)

问题:(用于int_comp的测试)

ia =0 ib =0 ia =0

谢谢你的帮助

EN

回答 1

Stack Overflow用户

发布于 2016-03-17 15:54:09

以十进制整数开头的字符串的qsort()比较回调应该如下所示:

代码语言:javascript
复制
static int int_cmp(const void *a, const void *b) 
{
  const long la = strtol(a, NULL, 10);
  const long lb = strtol(b, NULL, 10);
  if(la < lb)
    return -1;
  return la > lb;
} 

不要在return中使用减法,这会导致整数溢出错误。

还有, in C

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36064956

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档