gpt4 book ai didi

c - 在 strlen 中使用短路或电路?

转载 作者:太空宇宙 更新时间:2023-11-04 06:11:58 26 4
gpt4 key购买 nike

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

关于c - 在 strlen 中使用短路或电路?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54242343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com