qsort分段错误

时间:2012-02-11 07:35:30

标签: c strcmp qsort

所以我正在开发一个函数,该函数从stdio读入函数,并继续以 n 字符块的形式读取字符。

到目前为止,我已经知道所有内容都存储在名为buffer的字符数组中。对于下一步,我需要对n个字符的每个块进行排序。例如,如果n = 5,字符串cats / ndogs / n应该被拆分为cats / n dogs / n,然后qsort()需要按字母顺序排列它。这就是我打电话qsort()的方式:

qsort (buffer, (line-2)*n*(sizeof(char)),n,compare);

其中(line-2)*n*sizeof(char)给出数组缓冲区中的项目总数;在这种情况下为10。

这是我的比较功能:

int compare (const void * a, const void * b)
{
   return (strcmp(*(char **)a, *(char **)b));
}

然而,当我运行它时,我总是在strcmp()中得到一个seg错误。有什么想法吗?


这是加载代码:

while (!feof(stdin))
{
    for (i = 0; i < n; i++)
    {
        char l = getchar();
        if (l != EOF)
        {
            if ((i == 0) && (line != 1))
            {
                success = (int *)realloc(buffer, line*n*(sizeof(char)));
            }
            buffer[(n*(line-1))+i] = l;
        }
     }
     line = line + 1;
}

2 个答案:

答案 0 :(得分:1)

愚蠢的问题,但你的字符串是否空终止?你似乎最后只有一个换行符。

另外,你可能只需要&#34; strcmp((char *)a,(char *)b)&#34;因为额外的*看起来对我来说是多余的。

答案 1 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char buffer[] ="333000222555111777888666999444";

int mycmp(void *l, void*r);
int main(void)
{
/* note: sizeof buffer is 31,
** but the integer division will round down
** , ignoring the extra nul-byte */
qsort(buffer, (sizeof buffer/3), 3, mycmp);
printf ("[%s]\n", buffer);

return 0;
}

int mycmp(void *l, void *r)
{
return memcmp(l,r,3);
}