我有一个非常简单的代码:
secret[]="abcdefgh";//this is declared in different function and is random word
int len=strlen(secret);//ofc it is 8 in this case
char word[len];
for(int a=0;a<len;a++){//expecting this will put '_' at positions 0-7
word[a]='_';
}
printf("%d %s",(int)strlen(word),word);
但是,strlen(word)
返回 11 并且 word
包含 "________@"
,因此存在一些明显的内存泄漏,我可以看。任何想法?
最佳答案
此字符数组由字符串字面量初始化
secret[]="abcdefgh";
有 9 个元素,因为它还包括字符串文字的终止零。所以上面的定义等同于
secret[9]="abcdefgh";
函数 strlen
返回字符数组中终止零之前的元素数。所以在这个声明中
int len=strlen(secret);
变量 len
由 8
初始化
结果声明
char word[len];
相当于
char word[8];
在这个循环中
for(int a=0;a<len;a++){//expecting this will put '_' at positions 0-7
word[a]='_';
}
数组的所有元素都设置为 '_'
。 arry 没有终止零。因此,将函数 strlen
应用于数组具有未定义的行为。
你可以用下面的方式改变循环
int a = 0;
for(;a<len - 1;a++){//expecting this will put '_' at positions 0-7
word[a]='_';
}
word[a] = '\0';
在这种情况下,函数 strlen
将返回数字 7
,程序将是合式的。
关于C 字符数组的长度与预期不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29297418/