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

Does C have a shorthand way of initialize a struct with malloc and set its fields?

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

result = (node*)malloc(sizeof(node));
result->fx = (char*)malloc(sizeof(char) * 2);
result->fx[0]='x'; result->fx[1]='[=11=]';
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;

有没有 shorthand 的方法?换句话说,有没有办法像我在 C++ 中那样做?

result = new node { new char [] {'x','[=13=]'}, 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) ...

哪个更易读,更简洁。

您不能拥有两个嵌套的 malloc 并一次性初始化所有内容。但是我会建议以下设计:

typedef struct node
{
    char fx[2], op[2];    // first byte being null indicates not-present
    struct node *gx, *hx;
} node;

然后你可以更简单地写:

node *result = malloc( sizeof *result );

if ( !result )
    errorhandling......

// C89
node temp = { "x" };
*result = temp;

// C99
*result = (node){ .fx = "x" };

C99 示例使用 复合文字 指定初始值设定项,它们在 C 中而非 C++ 中。有关更多讨论,请参阅 How to initialize a struct in ANSI C

您不必使用指定的初始值设定项,但它减少了出错的可能性。任何未显式初始化的结构成员都将像 0.

一样被初始化

在这两种情况下,理论上的临时对象都会被优化掉,所以这个解决方案根本不应该被认为是低效的。