【发布时间】:2018-02-10 14:26:12
【问题描述】:
我在使用 C memset api 时按照How to memset char array with null terminating character? 添加了一个空终止符。
代码有效;由于空终止符,我不再将奇数的内存字符添加到我的 malloc 字符数组的末尾。
/* memset does not add a null terminator */
static void yd_vanilla_stars(size_t *number_of_chars, char *chars_to_pad)
{
memset(chars_to_pad, 0, *number_of_chars+1);
memset(chars_to_pad,'*',*number_of_chars);
}
有没有更优雅的方式来达到同样的效果?
【问题讨论】:
-
如果您使用
malloc()为您的数组分配,为什么不使用calloc()来获得零初始化分配? -
@DavidBowling.:是的,我也说了同样的话——我猜 OP 不喜欢它。
-
感谢@DavidBowling。 Calloc 更整洁。我可以删除此代码。
-
请不要在问题中编辑解决方案。相反,您可以在“答案”框中发布答案,或接受已发布的答案