C 字符数组的长度与预期不同

标签 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]='_';
}
printf("%d %s",(int)strlen(word),word);

但是,strlen(word) 返回 11 并且 word 包含 "________@",因此存在一些明显的内存泄漏,我可以看。任何想法?

最佳答案

此字符数组由字符串字面量初始化

secret[]="abcdefgh";

有 9 个元素,因为它还包括字符串文字的终止零。所以上面的定义等同于

secret[9]="abcdefgh";

函数 strlen 返回字符数组中终止零之前的元素数。所以在这个声明中

int len=strlen(secret);

变量 len8 初始化 结果声明

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/

相关文章:

java - 将新对象分配给通用数组索引

arrays - 如何使用 sequelize 在 Postgresql 中搜索具有多个搜索值的数组?

javascript - 如何在 for 循环中对具有精确索引的元素重复迭代?

java - 标记化字节数组

c - 带指针的链表 C

c - 如何让案例2记住案例1在文件中保存了什么?

c - 为什么 GCC 不对无法访问的代码发出警告?

javascript - 没有固定大小的 JS 多维数组

c - 使用 gnu gcc 编译器定义类型

c - 外部变量是如何定义的?