结构体的正确内存分配
以这种方式定义一个结构体,我需要分配内存
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;
}
Having a struct defined in a such way, I need to allocate memory
typedef struct string_collection {
char **c;
size_t current, allocated;
} TSC, *ASC;
So I came with this code, is it right or I missed something? First allocating struct descriptor and then enough space for d pointers to string
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑的代码本质上是正确的,尽管我与您有一些风格上的差异(例如不执行 typedef 来隐藏对象的“指针”,不使用 malloc/calloc 调用中分配的对象的大小,以及其他一些东西)。
您的代码“清理”了一下:
The code as edited is essentially correct, though I have several stylistic differences with you (such as not doing a typedef to hide the "pointerness" of an object, not using the size of the allocated object in the malloc/calloc call, and a few other things).
Your code, "cleaned up" a bit:
只要将
x
替换为sc
,在我看来就可以了。但是,您不应该在 C 中强制转换malloc
的返回值(了解更多信息 此处)。我会改为使用该行:您可以对 x->c 指向 (
char*
) 的类型的大小执行相同的操作。As long as
x
is replaced withsc
, it looks ok to me. You shouldn't, however, cast the return ofmalloc
in C (read more here). I would instead have for that line:You can do the same for the size of type
x->c
points to (char*
).