【发布时间】:2021-10-21 14:28:17
【问题描述】:
我已经在 C 中运行了这段代码,
char *bracket_by_len(char *output, char *word, int length)
{
if(strlen(word) < 5) {
output[0] = '<';
output[1] = '<';
/*int i = 2;
while(i != (strlen(word) + 2)) {
output[i] = word[i - 2];
i += 1;
}*/
strncat(output, word, strlen(word));
strcat(output, ">>");
return output;
} else {... not using them as 4 letter word for input}
int main()
{
char word[40], output[40]; // word is not used.
printf("%s \n.", bracket_by_len(output, "word", 20);
return 0;
}
实际代码是这样的:Input code. 然后我写了
return output;
我用这个打印出来的
printf("Based on size, \t %s.\n", output);
输出如下:
Based on size, <<^S>>.
开头有一些随机字符。当我将 strncat() 函数替换为 while 循环并手动复制单词的字母时,输入没问题。
提前致谢。
【问题讨论】:
-
输出和字是如何定义的?
-
output是如何声明和初始化的?请发帖minimal reproducible example。 -
你能展示整个代码吗?为什么从
output[1]而不是output[0]开始? -
output[2] = 0;丢失,需要生成一个以零结尾的字符串。strcpy(output, "<<");更有意义。 -
@shrewmouse,“新人”不是借口。如果他是新来的,他应该阅读How do I ask a good question?。 Downvotes 确实反映了问题的质量或有用性,并且不是个人的。顺便说一句,它甚至不消耗声望,因为你不能低于 1。