gpt4 book ai didi

c - 如何在 C 中的 char* 字符串末尾粘贴 null

转载 作者:行者123 更新时间:2023-11-30 20:02:37 25 4
gpt4 key购买 nike

char* s = (char*)malloc(5);

向字符串添加可变字节数(数字)的一些处理。例如 *s = 50;

我现在需要以 null 终止字符串。这有效。

*(s+1) = 0;

但是有没有更优雅的方式呢?

根据评论,这看起来像是这样做的方法

char* getvalue(char* str) {
while((*str++ = getnextchar()) != 'H')
;

*str = '\0'; /* null terminate */

return str;
}

最佳答案

使用calloc而不是malloc。这会将内存设置为零。

关于c - 如何在 C 中的 char* 字符串末尾粘贴 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11486533/

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