简体   繁体   English

qsort分割故障

[英]qsort segmentation fault

So I'm working on a program where the function reads in from stdio, and keeps reading in characters in chunks of n characters. 因此,我正在开发一个程序,该函数从stdio读取数据,并以n个字符的块的形式继续读取字符。

So far I've gotten it so that everything is stored in a character array called buffer. 到目前为止,我已经掌握了所有内容,并将其存储在一个称为buffer的字符数组中。 For the next step, I need to sort each chunk of n characters. 下一步,我需要对n个字符的每个块进行排序。 For example the string cats/ndogs/n should be split as cats/n dogs/n if n =5, and then qsort() needs to alphabetize it. 例如,如果n = 5,则应将字符串cats / ndogs / n拆分为cats / n dogs / n,然后qsort()需要将其按字母顺序排序。 This is how I'm calling qsort() : 这就是我调用qsort()

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

Where (line-2)*n*sizeof(char) gives the total number of items in the array buffer; 其中(line-2)*n*sizeof(char)给出数组缓冲区中的项目总数; 10 in this case. 在这种情况下为10。

This is my compare function: 这是我的比较功能:

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

When I run this, however, I always get a seg fault in strcmp() . 但是,当我运行它时,我总是在strcmp()遇到段错误。 Any ideas why? 有什么想法吗?


This is the loading code: 这是加载代码:

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;
}

Silly question, but are your strings null terminated? 愚蠢的问题,但是您的字符串是否以null结尾? You seem to only have a newline on the end. 您似乎最后只有换行符。

Also, you probably only need "strcmp((char *)a, (char *)b)" as the extra *s look to be redundant to me. 另外,您可能只需要“ strcmp((char *)a,(char *)b)”,因为多余的* s对我来说是多余的。

#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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM