views:

563

answers:

3

Hi all

I have been trying to write a C program which generates all possible permutations of a string (eg 123 in code below). I succeeded but it generates some garbage values after each possible permutation. Please help me in finding the possible cause. Is it something to do with initialization? Code:

#include <stdio.h>
void permute(char number[],char out[],int level,int used[]);
int main()
{   
    char number[] = "123";
    char out[3] = "asd";    // Random initialization
    int used[] = {0,0,0};    // To check if number has been used in the string output
    permute(number,out,0,used);
}   
void permute (char number[],char out[],int level,int used[])
{
    if (level == 3)
    {
     printf("%s\n",out);
     return;
    }
    int i;
    for(i = 0; i < 3;i++ )
    {
            if( used[i] == 1) continue;
            out[level] = number[i];
            used[i] = 1;
            permute( number, out, level + 1,used );
            used[i] = 0;
    }  
}
+1  A: 

My C is very rusty, but my guess is that it is caused by the fact that your character array is not null terminated.

One option is to print out each character individually:

if (level == 3)
{
    int p;
    for(p=0 ; p<3 ; p++) {
        printf("%c", out[p]);
    }
}
Peter Richards
putchar() or putc() might be a bit better than a full printf(), not that it matters an awful lot.
Chris Lutz
Yup it works now! I null terminated it and it works fine now. This are nothing but consequences of switching from Java to C for a while where things are so taken care of itself! Thanks a lot!
shuby_rocks
@Chris Lutz : Like I said, my C is very rusty :-D
Peter Richards
A: 

If you think it should stop printing the contents of out after the first three characters, ask yourself how it would know to do so.

Marty Lamb
Thnx for the comments! I thought since I have set the limits of array to be 3, it will automatically know where to stop. I get it now :-).
shuby_rocks
C *never* automatically knows where to stop. ;-)
David Zaslavsky
LOL. I love that about C.
euphoria83
+2  A: 

char out[3] = "asd"; // Random initialization

Change this to out[4] so you have room for the terminating \0 character, and it should work as you expect it to.

Brian Mitchell
Or make it out[].
sigjuice