C字符数组的长度与预期长度不同
我有一个非常简单的代码:C字符数组的长度与预期长度不同,c,arrays,C,Arrays,我有一个非常简单的代码: 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]='_'; }
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);
secret[]=“abcdefgh”//这是在不同的函数中声明的,是随机字
int len=strlen(秘密)//ofc在这种情况下是8
字符字[len];
对于(inta=0;a,乍一看,您似乎忘记了在字符数组(指针)的末尾添加null
根据我的经验,这会导致缓冲区溢出或堆栈损坏。您只需要nul终止字符串,将len增加1,然后nul终止字符串
#include <stdio.h>
#include <string.h>
int main(void)
{
char secret[]="abcdefgh";
int len=strlen(secret);
char word[len+1];
for(int a=0;a<len;a++)
{
word[a]='_';
}
word[a]=0; //or word[a]='\0'
printf("%d %s",(int)strlen(word),word);
return 0;
}
#包括
#包括
内部主(空)
{
char secret[]=“abcdefgh”;
int len=strlen(秘密);
字符字[len+1];
对于(int a=0;a没有空间放置'\0'
// "abcdefgh"
// 01234567
您需要为NUL终止符定义带空格的单词
char word[len + 1];
// "abcdefgh"
// 012345678 -- word[8] gets '\0'
一加一改
字符字[len];需要使用字符字[len+1]进行更改
在最后一行printf之前添加一行world[len]='\0'
也就是说,此字符数组由字符串文本初始化
secret[]="abcdefgh";
有9个元素,因为它还包括字符串文本的终止零
secret[9]="abcdefgh";
char word[8];
函数strlen
返回字符数组中在终止零之前的元素数
int len=strlen(secret);
char word[len];
变量len
由8
结果声明
int len=strlen(secret);
char word[len];
相当于
secret[9]="abcdefgh";
char word[8];
在这个循环中
for(int a=0;a<len;a++){//expecting this will put '_' at positions 0-7
word[a]='_';
}
在这种情况下,函数strlen
将返回数字7
,程序将格式良好。阅读手册了解printf
以及%s
的含义。还应注意C-“字符串”s需要以0
-结尾char
-数组。word
应该以null结尾。您忘记了字符串不仅是您在其中看到的字符,它还包含一个标记字符串结尾的特殊字符'\0'
。所有字符串函数都希望此特殊字符位于结尾,否则它们将超出字符串的结尾,您将有。char-word[len+1];
…word[len]=0;
或word[a]=0;
在for-loop之后。为什么会导致内存泄漏?没有动态内存分配正确,但是在C/C++中,如果不在字符数组的末尾放置null,则会得到随机大小的垃圾。例如,如果您的字符数组是5,并且没有在其末尾放置null,则可能会得到大小为100的垃圾。这就是为什么Calls null终止。无论动态分配与否,归零终止失败都不会导致内存泄漏。其他错误模式,如缓冲区溢出或堆栈损坏,都是典型的后果。@IInspectable,编辑了这篇文章。你是对的,我的意思正是这样。