将输入字符串转换为数组并按字母顺序对字符串数组进行排序

时间:2013-05-23 09:24:03

标签: c segmentation-fault

我想输入一些字符串并按字母顺序排序,最多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]);
}

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

尝试像这样声明2d数组。它对我有用。

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

for (i = 0; i < 100; i++)
{
    sequences[i] = (char*)malloc(50 * sizeof(char));
}