gpt4 book ai didi

c - snprintf() 不适用于就地修改字符串

转载 作者:行者123 更新时间:2023-12-01 08:13:26 24 4
gpt4 key购买 nike

char symbols[16] = "";
int index = 0;
while (1)
{
if (index % 2)
snprintf(symbols, sizeof symbols, "a%s", symbols);
else
snprintf(symbols, sizeof symbols, "b%s", symbols);

index++;

printf("%s\n", symbols);
}

输出的样子:a => bb => aaa => bbbb

我想要输出看起来:a => ba => aba => baba

最佳答案

这是未定义的行为。来自 C99 标准部分 7.19.6.5 The snprintf function:

The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by argument s) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.

您需要制作一份 symbols 的副本,以用作 snprintf() 调用中的参数:

char symbols[16] = "";
char symbols_copy[16];
int index = 0;
while (index++ < 15)
{
memcpy(symbols_copy, symbols, sizeof(symbols));

if (index % 2)
snprintf(symbols, sizeof symbols, "a%s", symbols_copy);
else
snprintf(symbols, sizeof symbols, "b%s", symbols_copy);

printf("%s\n", symbols);
}

查看演示 http://ideone.com/GvnW7D .

关于c - snprintf() 不适用于就地修改字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13503662/

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