0

The following code is to sort each string in a set(sort its characters), then sort all the strings in the set. But it is giving me segmentation fault..

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int comp ( const void *a, const void *b)
{
return strcmp ( *(char **) a, *(char **) b );
}


int compare(const void* a, const void* b)
{  return *(char*)a - *(char*)b; }
void printAnagramsTogether( char * str[], int size)
{
int i, j;
//qsort ( str, size, sizeof (str[0]), comp);
for (i=0; i<size; i++)
        qsort((void *)str[i], strlen(str[i]), sizeof (char), compare);

qsort ( str, size, sizeof (str[0]), comp);

}

int main()
{
char* wordArr[] = {"cat", "dog", "tac", "god", "act"};
int size = sizeof(wordArr) / sizeof(wordArr[0]);
printAnagramsTogether(wordArr, size);
return 0;
}
bhavneet
  • 51
  • 2
  • 11
  • 2
    If you want to use C++, then use the C++ library, like [`std::string`](http://en.cppreference.com/w/cpp/string/basic_string) and [`std::sort`](http://en.cppreference.com/w/cpp/algorithm/sort). C and C++ are two very different languages. – Some programmer dude Apr 02 '13 at 02:51
  • Or at least use dynamic data structures, as long as it does not try to write to read-only memory, there's no segmentation fault (in most cases). – Dmytro Apr 02 '13 at 02:53

1 Answers1

0

Run this

int main()
{
    char *arr[] = {"rony", "phony", "nop"};
    arr[0][0] = 1;
}

it crashes because the strings are constant (i suppose stored in text segment of code).

Dmytro
  • 5,068
  • 4
  • 39
  • 50
  • 1
    can you please explain reasoning behind downvote? I explained exactly what you have done -- tried to write to read-only memory. – Dmytro Apr 02 '13 at 02:52