gpt4 book ai didi

c - C 是否有使用 malloc 初始化结构并设置其字段的简写方法?

转载 作者:太空狗 更新时间:2023-10-29 14:53:15 24 4
gpt4 key购买 nike

我有一段乱七八糟的代码,比如

result = (node*)malloc(sizeof(node));
result->fx = (char*)malloc(sizeof(char) * 2);
result->fx[0]='x'; result->fx[1]='\0';
result->gx = NULL; result->op = NULL; result->hx = NULL;

我在这里初始化一个类型的元素

typedef struct node
{
char * fx; // function
struct node * gx; // left-hand side
char * op; // operator
struct node * hx; // right-hand side
} node;

有没有简写的方法来做到这一点?换句话说,有没有办法像我在 C++ 中那样做?

result = new node { new char [] {'x','\0'}, NULL, NULL, NULL };

最佳答案

您可以编写自己的包装函数:

static node *getNewNode(char *fx) {
node *p = calloc(1, sizeof *p);
if(p && fx) {
p->fx = malloc(strlen(fx) + 1);
if(!p->fx) {
free(p);
p = null;
} else {
strcpy(p->fx, fx);
}
}
return p;
}

稍后您可以将其称为:

node *result = getNewNode("x");
if(result) ...

哪个更易读,更简洁。

关于c - C 是否有使用 malloc 初始化结构并设置其字段的简写方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30450005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com