0

以这种方式定义结构后,我需要分配内存

typedef struct string_collection {
    char **c;
    size_t current, allocated;
} TSC, *ASC;

所以我带着这个代码来了,是对的还是我错过了什么?首先分配结构描述符,然后为指向字符串的 d 指针分配足够的空间

ASC AlocSC(size_t d)
{
    ASC sc;

    sc = (TSC*) malloc(sizeof(TSC));
    if (!sc) return NULL;

    sc->c = calloc(d, sizeof(char *));

    if (!sc->c) {
        free(sc);
        return NULL;
    }

    sc->current = 0;
    sc->allocated = d;

    return sc;
}
4

2 回答 2

2

只要x替换为sc,对我来说就可以了。但是,您不应该在 C 中使用 return (在此处malloc阅读更多内容)。我会改为使用该行:

sc = malloc(sizeof(*sc));

您可以对x->c指向 ( char*) 的类型点的大小执行相同操作。

于 2011-12-08T21:24:24.317 回答
2

编辑后的代码基本上是正确的,尽管我与您有几个风格上的差异(例如不使用 typedef 来隐藏对象的“指针性”,不使用 malloc/calloc 调用中分配对象的大小,以及其他几件事)。

你的代码,“清理”了一下:

TSC *AlocSC(size_t d)
{
    TSC *sc = malloc(sizeof *sc);
    if (!sc) return NULL;

    sc->c = calloc(d, sizeof *sc->c);
    if (!sc->c) {
        free(sc);
        return NULL;
    }

    sc->current = 0;
    sc->allocated = d;

    return sc;
}
于 2011-12-08T21:26:38.740 回答