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");
我该怎么做?
答案 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");
}