我必须在read_triplet中释放双重音吗?我该怎么做?

时间:2012-04-23 06:41:41

标签: c

#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中,我将doublet中的指针复制为triplet。如何在不使用引用计数或垃圾收集器库的情况下从main释放双重内存?

1 个答案:

答案 0 :(得分: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);
}