我有一个混乱的代码块,如
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 };
答案 0 :(得分:7)
您可以编写自己的包装函数:
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) ...
哪个更易读,更少杂乱。
答案 1 :(得分:5)
您不能拥有两个嵌套的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
。
在这两种情况下,理论临时对象都将被优化掉,所以这个解决方案根本不应该被认为是低效的。