There are some problems with
Code:
char *swich(char *topermute, int x, int y)
{
char *newstring;
newstring = (char *) malloc (sizeof(*topermute));
topermute = newstring;
newstring[x] = newstring[y];
newstring[y] = topermute[x];
return topermute;
}
First: the size of array newstring should be strlen(topermute)+1, so that it can hold all its characters and also the terminating '\0'.
(Note that sizeof(*topermute) is the size of a char.)
Second: Copy topermute into newstring.
Third: perform the character switch in newstring.
Fourth: return the pointer to the permuted string.
so, it could be something like:
Code:
char *swich(char *topermute, int x, int y)
{
char *newstring;
newstring = (char *) malloc (strlen(topermute)+1);
strcpy(newstring, topermute);
newstring[x] = newstring[y];
newstring[y] = topermute[x];
return newstring;
}
Now, this function is called many times, and allocates new storage every time. It is your responsibility to deallocate all memory before your program exits. So, function permute() should free() the memory after the call to swich().
Something like this should work:
Code:
void permute(char *topermute, int place)
{
int nextchar;
char *switched_string;
if(place == strlen(topermute) -1)
{
printf("%s\n", topermute);
}
for(nextchar = place; nextchar < strlen(topermute); nextchar++)
{
switched_string = swich(topermute, place, nextchar);
permute(switched_string, place+1);
free(switched_string);
}
}
Dave