0

I want to input some strings and sort them alphabetically, at most 100 strings and the length of each string is less than 50, but I get a Segmentation fault.

#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
  • In your comp function, before you call strcmp, try to print the arguments, to see if they really are what you think they are. Or use a debugger. Commented May 23, 2013 at 9:26
  • Don't think you can do that with 2-D array. Think about creating array of char * for each string. Commented May 23, 2013 at 9:28

2 Answers 2

3

change

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

to

return strcmp ((const char *) a, (const char *) b);
...
qsort(sequences, nr_of_strings, sizeof(char [50]), comp);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for comment, I have tried this, still Segmentation fault.
@jfly still Segmentation fault. Surely? It's work fine to me.
Sorry, I only change 'qsort(sequences, nr_of_strings, sizeof(char *), comp);' to 'qsort(sequences, nr_of_strings, sizeof(char [50]), comp);'. It works fine.
1

Try to declare the 2d array like this. It worked for me.

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.