shuby_rocks
shuby_rocks

Reputation: 801

Where's the bug in my C program which generate all possible permutations of a string?

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;
    }       
}

Upvotes: 1

Views: 1001

Answers (3)

Brian Mitchell
Brian Mitchell

Reputation: 2288

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.

Upvotes: 2

Marty Lamb
Marty Lamb

Reputation: 1988

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.

Upvotes: 0

Peter Richards
Peter Richards

Reputation: 629

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]);
    }
}

Upvotes: 2

Related Questions