qsort分段错误
因此,我正在开发一个程序,其中该函数从 stdio 读取,并以 n 个字符的块形式不断读取字符。
到目前为止,我已经得到了它,以便所有内容都存储在称为缓冲区的字符数组中。对于下一步,我需要对 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()
中遇到段错误。有什么想法吗?
这是加载代码:
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;
}
So I'm working on a program where the function reads in from stdio, and keeps reading in characters in chunks of n characters.
So far I've gotten it so that everything is stored in a character array called buffer. For the next step, I need to sort each chunk of n characters. 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. This is how I'm calling 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; 10 in this case.
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()
. 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
愚蠢的问题,但是你的字符串是否以 null 结尾?你似乎最后只有一个换行符。
另外,您可能只需要“strcmp((char *)a, (char *)b)”,因为额外的 * 对我来说看起来是多余的。
Silly question, but are your strings null terminated? 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.