这怎么可能,这个字符串的长度增加了吗? [英] How is it possible that the length of this string is increasing?
问题描述
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * odd(const char * S, char * dest);
int main()
{
char * source = "abcdefghijklmnopacegiacegi";
unsigned int length = strlen(source);
char dest[length];
printf("%s\n",odd(source, dest));
}
char * odd(const char * source, char * dest)
{
int count = 0;
unsigned int length = strlen(source);
for(int i = 0; i < length; i++)
{
if( (source[i] %2 )!= 0)
{
dest[count] = source[i];
count++;
}
}
return dest;
}
的目标寄存器的尺寸增大和源的长度之后产生为任何值垃圾
the size of dest increases and produces garbage for any values after the length of source
推荐答案
您必须手动包括结束 \\ 0
字符串,即在年底添加
,您必须添加:
You have to manually include the ending \0
to the string, that is, at the end of add
, you have to add:
dest[count] = '\0';
您知道吗,串用C长度占搜索的 \\ 0
字符。你必须包括那些在每个C字符串的末尾中的一个。如果不是,该字符串可以包含任何垃圾,直到第一个 \\ 0
将被打印出来。
You know, the length of strings in C is accounted searching for the \0
character. You have to include one of those at the end of each C string. If not, the string may contain any garbage till the first \0
that will be printed.
最后,当创建 DEST
,你还增加预留空间的长度在一个容纳,结束0字符。在的strlen
不计,结束0字符。
Finally, when creating dest
, you have also to increase the length of the reserved space in one to accomodate that ending 0 character. The strlen
does not count that ending 0 character.
这篇关于这怎么可能,这个字符串的长度增加了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!