0
#include <stdio.h>
#include <stdlib.h>

static char *ones[] = {
    "",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine"
};

static char *teens[] = {
    "",
    "eleven",
    "twelve",
    "thirteen",
    "forteen",
    "fifteen",
    "sixteen",
    "seventeen",
    "eighteen",
    "nineteen"
};

static char *tens[] = {
    "",
    "ten",
    "twenty",
    "thirty",
    "forty",
    "fifty",
    "sixty",
    "seventy",
    "eighty",
    "ninety"
};

static char *powers[] = {
    "thousand",
    "million",
    "billion",
    "trillion",
    "quadrillion",
    "quintillion",
    "sextillion",
    "septillion",
    "octillion",
    "nonillion",
    "decillion"
};

char** read_doublet(int a, int b) {
    char** doublet = malloc(2 * sizeof (char*));
    if (doublet != NULL) {
        if (a == 0 && b > 0) {
            doublet[0] = ones[0];
            doublet[1] = ones[b];
        } else if (a == 1 && b > 0) {
            doublet[0] = teens[0];
            doublet[1] = teens[b];
        } else if (a > 0 && b == 0) {
            doublet[0] = tens[0];
            doublet[1] = tens[a];
        } else if (a > 0 && b > 0) {
            doublet[0] = tens[a];
            doublet[1] = ones[b];
        } else {
            doublet[0] = ones[0];
            doublet[1] = ones[0];
        }
        return doublet;
    }
    return NULL;
}

char** read_triplet(int a, int b, int c) {
    char** triplet = malloc(3 * sizeof(char*));
    if(triplet != NULL) {
        triplet[0] = ones[0];

        if(a > 0) {
            triplet[0] = ones[a];
        }

        char** doublet = read_doublet(b, c);
        if(doublet != NULL) {
            triplet[1] = doublet[0];
            triplet[2] = doublet[1];
        }

        return triplet;
    }

    return NULL;
}

int main(void) {
    printf("%s %s %s %s\n", teens[1], ones[1], tens[1], powers[1]);

    char** answer = read_triplet(2, 1, 2);
    if (answer != NULL) {
        printf("%s %s %s", answer[0], answer[1], answer[2]);
        free(answer);
    }
    return (EXIT_SUCCESS);
}

上記のコードでは、read_triplet で、ダブレット内のポインターをトリプレットにコピーします。参照カウントまたはガベージ コレクター ライブラリを使用せずに、メインからダブレット メモリを解放するにはどうすればよいですか?

4

1 に答える 1

0

コードを書くのは良くないパターンだと思います。

char** read_triplet(int a, int b, int c) {
    char** triplet = malloc(2 * sizeof(char*));
    if(triplet != NULL) {
        triplet[0] = ones[0];

        if(a > 0) {
            triplet[0] = ones[a];
        }

        char** doublet = read_doublet(b, c);
        if(doublet != NULL) {
            triplet[1] = doublet;
        }

        return triplet;
    }

    return NULL;
}

int main(void) {
    printf("%s %s %s %s\n", teens[1], ones[1], tens[1], powers[1]);

    char** answer = read_triplet(2, 1, 2);
    if (answer != NULL) {
        printf("%s %s %s", answer[0], answer[1][0], answer[1][1]);
        free(answer[1])
        free(answer);
    }
    return (EXIT_SUCCESS);
}
于 2012-04-23T07:06:43.877 に答える