我得整理一下:
第一章**路
它包含如下一行:
807
每行在开头有一个数字,我需要用它对它们进行排序
但我不知道如何使用strtol是快速排序cmp_fct
代码示例:
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;
}我如何使用快速排序:
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
谢谢你的帮助
发布于 2016-03-17 15:54:09
以十进制整数开头的字符串的qsort()比较回调应该如下所示:
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。
https://stackoverflow.com/questions/36064956
复制相似问题