[英]C: printf char* return weird last char
我试图理解为什么在我的printf()
之后有一个奇怪的角色
char* extract_word()
{
char* sentences = "hi! i'm a banana!";
int starts = 4;
int ends = 12;
int count;
int nb_char = ends-starts+1;
char* word = malloc(nb_char);
printf("\n\n%d\n",ends-starts);
for(count = starts; count < ends;count++)
{
word[count-starts] = sentences[count];
printf("%c == \n",sentences[count]);
}
word[count-starts+1] = '\0';
printf("\n\n%s",word);
return word;
}
printf
返回:
8 i == ' == m == == a == == b == a == i'm a bau
如果删除'\\0'
则会得到类似以下内容:
'ma ba¨Á£´
如果删除\\0
printf无法知道字符串结束,并且将不断增加指针,直到看到空值为止,并且冒着出现分段错误的风险。
对于结尾没有0的字符串,可以使用snprintf
另外,对于您要实现的目标,还有memcpy
或strncpy
有关更多详细信息,请参见手册页。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.