1

guys, I want to make a program to generate all combination elements. for example if user input (n) = 3, so the output must be like this :

1
12
123
13
2
23
3

I have a problem to concat integer and string inside recursive function..

Code :

#include <stdio.h>

void rekursif(int m, int n, char angka[100]){
    int i;
    for(i=m; i<=n; i++){
        sprintf(angka, "%s %d", angka, i);
        printf("%s \n", angka);
        rekursif(i+1,n,angka);
    }
}

int main(){
    rekursif(1,5,"");
    return 0;
}

when I run the program, command prompt is not responding. I guess, the problem is in concation ( sprintf(angka, "%s %d", angka, i); ) please help me to solve this problem. thank you :)

1 Answer 1

1

By passing "" as the function argument, you are trying to modify a string literal, which is undefined behavior. Instead, do:

int main(){
    char str[100];
    rekursif(1, 5, str);
    return 0;
}

Be careful with buffer overflow in practice.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your response. Command prompt is running well. But if I input n = 3 the result is like this 1 12 123 1233 12332 123323 1233233 I realize that I was wrong, the variable angka must be reset in specific condition. is there another way to solve this problem beside sprintf function? thanks
@stranger Since you can debug the program now, it's best that you try it first before asking for help.
Sorry, I just try debug the program right now, and it solved. Thanks. I just need to back up the variable angka into another variable before concation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.