[英]qsort segmentation fault
因此,我正在開發一個程序,該函數從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()
遇到段錯誤。 有什么想法嗎?
這是加載代碼:
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;
}
愚蠢的問題,但是您的字符串是否以null結尾? 您似乎最后只有換行符。
另外,您可能只需要“ 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.