Ask about printing strings using the C language recursive function.

Asked 2 years ago, Updated 2 years ago, 155 views

If you output a string of length 3 using two alphabets ab,

aaa
aab
aba
abb
baa
bab
bba
bbb

You have to make it come out like this. A two-dimensional character array is dynamically assigned, and the Distr function ensures that a and b are stored according to the rules. However, if you turn it in Visual Studio, if you enter 3, the program is forced to end, and if you enter 4,

 if (n > 1) {       
    while (len > i) {
         for (i = my_pow(2, n); i < 3*my_pow(2, n-1); i++)
            strcat(dic[i], "a");            
        for (i = 3* my_pow(2, n-1); i < my_pow(2, n+1); i++)
            strcat(dic[i], "b");        
    }   
}

An exception has occurred here.

Is there an error that I didn't see? Then please save me.

#pragma warning (disable : 4996)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int my_pow(int base, int exp) {

    //You must create your own power function.

    int i, j;
    j = base;
    for (i = 0; i < exp - 1; i++)
        j = j * base;

    return j;
}

void Dicstr(char **dic, int n, int len)
{

    char ab[2][2] = { "a", "b" };
    int i = 0;
    int k;

    if (n == 1) {
        i = 0;
        while (i < len) {
            for (k = 0; k < 2; k++) {
                strcat(dic[i], ab[k]);
                i++;
            }
        }
        return;
    }
    if (n > 1) {
        for (i = 0; i < my_pow(2, n - 1); i++)
            strcat(dic[i], "a");
        for (i = my_pow(2, n - 1); i < my_pow(2, n); i++)
            strcat(dic[i], "b");
    }
    if (n > 1) {
        while (len > i) {
            for (i = my_pow(2, n); i < 3*my_pow(2, n-1); i++)
                strcat(dic[i], "a");
            for (i = 3* my_pow(2, n-1); i < my_pow(2, n+1); i++)
                strcat(dic[i], "b");
        }
    }
    if (n > 1)
        Dicstr(dic, n - 1, len);
}

void strPrint(char **str, int num) {

    int i;

    for (i = 0; i < my_pow(2, num); i++)
        printf("%s\n", str[i]);

}

int main(void) {

    int num = 0;
    int i;
    char **new;
    int len = 0;

    scanf("%d", &num);
    len = my_pow(2, num);

    new = (char **)calloc(len, sizeof(char *); //2D character array dynamic assignment
    for (i = 0; i < len; i++)
        new[i] = (char *)calloc(len, sizeof(char));

    Dicstr(new, num, len); // Functions that are arranged in dictionary order
    strPrint(new, num); //Function to output

    for (i = 0; i < len; i++) { //dynamic deallocation
        free(new[i]);
    }
    free(new);

    return 0;
}

c recursive string dynamic-allocation

2022-09-21 10:16

1 Answers

new[i] = (char *)calloc(len, sizeof(char));

I think we need to exceed the maximum length for the non-len string. Should I say 1024?


2022-09-21 10:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.