在内部使用短路OR电路吗?

时间:2019-01-17 18:42:54

标签: c malloc

result.author = (char *)malloc(sizeof(char)*strlen(temp->author));

strcpy(result.author, temp->author);

我正在做RPC,但这不是问题。 在这里,我想分配和复制字符串“ UNKNOWN”,如果temp为NULL,如下面的代码。

result.author = (char *)malloc(sizeof(char)*strlen(temp->author || "UNKNOWN"));

strcpy(result.author, temp->author || "UNKNOWN");

我该怎么做?

1 个答案:

答案 0 :(得分:4)

result.author = malloc(strlen(temp->author ? temp.author : "UNKNOWN") + 1);

strcpy(result.author, temp->author ? temp.author : "UNKNOWN");

它是的简写:

if(temp->author)
{
    result.author = malloc(strlen(temp->author) + 1);
    strcpy(result.author, temp->author);   
}
else
{
    result.author = malloc(strlen("UNKNOWN") + 1);
    strcpy(result.author, "UNKNOWN");   
}