0

我想输入一些字符串并按字母顺序对它们进行排序,最多 100 个字符串,每个字符串的长度小于 50,但出现分段错误。

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

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

int main()
{
    char sequences[100][50];
    int nr_of_strings;
    scanf("%d", &nr_of_strings);
    int i;
    for(i = 0; i < nr_of_strings; ++i)
        scanf("%s", sequences[i]);
    qsort(sequences, nr_of_strings, sizeof(char *), comp);
    for(i = 0; i < nr_of_strings; ++i)
        printf("%s\n", sequences[i]);
}
4

2 回答 2

3

改变

return strcmp (*(const char **) a, *(const char **) b);
...
qsort(sequences, nr_of_strings, sizeof(char *), comp);

return strcmp ((const char *) a, (const char *) b);
...
qsort(sequences, nr_of_strings, sizeof(char [50]), comp);
于 2013-05-23T09:42:16.283 回答
1

尝试像这样声明二维数组。它对我有用。

char** sequences;
int i;
sequences = (char**)malloc(100 * sizeof(char*));

for (i = 0; i < 100; i++)
{
    sequences[i] = (char*)malloc(50 * sizeof(char));
}
于 2013-05-23T09:40:42.143 回答