Here you go, champ. Notice my changes in red.
Code:
/*
** PERMUTE.C - prints all permutations of an input string
**
** adapted from public domain demo by Jon Guthrie for J. Uslander (4/1/2008).
**
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int charcmp(char *, char *);
void permute(char *, int, int);
void clrscr(void);
int main(void)
{
char string[1024];
int length;
char throwaway;
printf("Enter a single word string, using only letters and no spaces: ");
fflush(stdout);
fgets(string, sizeof(string), stdin);
length = strlen(string);
if (length != 0 )
{ /* It only works if they're printed in order */
qsort(string, length, 1, (int(*)(const void *, const void *))charcmp);
permute(string, 0, length);
printf("This program requires user to input a single word string(non-NULL).\n");
printf("Press ENTER to exit.\n");
fflush(stdout);
scanf("%c", &throwaway);
return 0;
}
else {
printf("This program requires user to input a single word string(non-NULL).\n");
printf("Press ENTER to exit.\n");
scanf("%c", &throwaway);
}
return 0;
}
/*
** This function prints all of the permutations of string "array"
** (which has length "len") starting at "start."
*/
void permute(char *array, int start, int len)
{
int j;
char *s;
if(start < len)
{
if(NULL == (s = malloc(len + 1))) /* Bug fixed by Stephan Wilms */
{
printf("\n\nMemory error!!!\a\a\n");
abort();
}
strcpy(s, array);
for(j=start ; j<len ; ++j)
{
int temp;
if((j == start) || (s[j] != s[start]))
{ /* For each character that's different */
/* Swap the next first character with... */
/* the current first */
temp = s[j];
s[j] = s[start];
s[start] = temp;
permute(s, start+1, len);
}
}
free(s);
}
else
{
printf("%s", array);
}
}
int charcmp(char *a, char *b)
{
return(*a - *b);
}
void clrscr(void)
{
//char a[80];
printf("\033[2J"); /* clear the entire screen*/
printf("\033[0;0f"); /* move cursor to the top left hand corner */
}