Reputation: 161
I'm trying to generate permutations of a string and store them in a pointer array
#include<stdio.h>
#include<string.h>
int count;
char *str[100];
/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
/* Function to print permutations of string
This function takes three parameters:
1. String
2. Starting index of the string
3. Ending index of the string. */
void permute(char *a, int i, int n)
{
int j;
if (i == n)
{
str[count++]=a;
printf("%s\n", str[count-1]);
}
else
{
for (j = i; j <= n; j++)
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j)); //backtrack
}
}
}
/* Driver program to test above functions */
int main()
{
char a[] = "ABC";
int i;
count=0;
permute(a, 0, 2);
for(i=0;i<count;i++)
printf("%s\n", str[i]);
return 0;
}
When I execute this, I get output as:
ABC ACB BAC BCA CBA CAB
ABC ABC ABC ABC ABC ABC
Why am i getting these different values for str in different functions?
Solved:
str[count++]=strdup(a);
or
converted *str[] to str[][] and then did strcpy(str[],a)
Upvotes: 0
Views: 69
Reputation: 908
You are editing 'a' in place. You should make a copy of each resulting permutation.
str[count++]=strdup(a);
Upvotes: 3