0

I am trying to run the following code for finding out permutations of a string:

void swapchar(char *a,char *b)
{
    char tmp;
    tmp=*a;
    *a=*b;
    *b=tmp;
}

void permute (char *a,int i,int n)
{
    if (i==n)
    {
        for (int k=0;k<(sizeof(a)/sizeof(a[0]));k++)
        {
            printf("\t%c",a[k]);
        }
        printf("\n");
    }
    else
    {
        for (int j=i;j<n;j++)
        {
            swapchar((a+i),(a+j));
            permute(a, i+1, n);
            swapchar((a+i),(a+j));
        }
    }
}

The output I get is something like:

K   N   L   U   A    <inverted ?> <inverted ?> <inverted ?>       
K   A   N   U   L    <inverted ?> <inverted ?> <inverted ?>
K   A   N   L   U    <inverted ?> <inverted ?> <inverted ?>   
K   A   U   N   L    <inverted ?> <inverted ?> <inverted ?>
K   A   U   L   N    <inverted ?> <inverted ?> <inverted ?>
K   A   L   U   N    <inverted ?> <inverted ?> <inverted ?>

Can you please explain to me where is my code going South that I am getting these junk characters at the end?

Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
  • 7
    `sizeof(a)` wont' work as you expected, it give you pointer size – Bryan Chen Sep 01 '14 at 21:56
  • I don't know if I should ask this in a separate question or not. How do I correct this code then? What is the correct way of getting the size of an array in c language? @BryanChen – Kunal Shrivastava Sep 01 '14 at 21:58
  • 1
    @KunalShrivastava, if you want to use the size of an array passed by pointer, you'll have to pass the size separately. – Samuel Edwin Ward Sep 01 '14 at 22:00
  • 2
    possible duplicate of [How to find the 'sizeof'(a pointer pointing to an array)?](http://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-an-array) – Samuel Edwin Ward Sep 01 '14 at 22:01

1 Answers1

2

The use of sizeof(a)/sizeof(a[0]) in your code does not do what you expect since the array you pass to the function "decays" to a pointer. Try passing the size of the array explicitly as one of the arguments.

downhillFromHere
  • 1,967
  • 11
  • 11