Mic*_*dge 5 c malloc struct initialization data-structures
我有一个混乱的代码块,如
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;
Run Code Online (Sandbox Code Playgroud)
我在哪里初始化一个类型的元素
typedef struct node
{
char * fx; // function
struct node * gx; // left-hand side
char * op; // operator
struct node * hx; // right-hand side
} node;
Run Code Online (Sandbox Code Playgroud)
这样做有简便的方法吗?换句话说,有没有办法像在C++中那样做?
result = new node { new char [] {'x','\0'}, NULL, NULL, NULL };
Run Code Online (Sandbox Code Playgroud)
你可以编写自己的包装函数:
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;
}
Run Code Online (Sandbox Code Playgroud)
稍后您可以将其称为:
node *result = getNewNode("x");
if(result) ...
Run Code Online (Sandbox Code Playgroud)
哪个更具可读性,更少杂乱.
您不能拥有两个嵌套的malloc并一次性初始化所有内容.不过我会建议以下设计:
typedef struct node
{
char fx[2], op[2]; // first byte being null indicates not-present
struct node *gx, *hx;
} node;
Run Code Online (Sandbox Code Playgroud)
然后你可以更简单地写:
node *result = malloc( sizeof *result );
if ( !result )
errorhandling......
// C89
node temp = { "x" };
*result = temp;
// C99
*result = (node){ .fx = "x" };
Run Code Online (Sandbox Code Playgroud)
C99示例使用复合文字和指定的初始值设定项,它们使用C而不是C++.有关更多讨论,请参见如何在ANSI C中初始化结构.
您不必使用指定的初始化程序,但可以减少出错的可能性.未显式初始化的任何结构成员都将被初始化,就像使用0.
在这两种情况下,理论临时对象都将被优化掉,所以这个解决方案根本不应该被认为是低效的.