C语言 在 strlen 内部使用短路或电路


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

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

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

我怎样才能做到这一点?

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");   
}

相关内容

  • 没有找到相关文章