c - 为什么我的字符串在初始化时会被连接起来?
问题描述
我正在尝试练习声明字符串,但我没有得到正确的输出。
#include <stdio.h> //Im using vscode and gcc
int main()
{
char k[]= "prac c";
char l[6]= "stop c"; //first initializing as size 6
char m[6]= "nice c";
printf("%s \n%s \n%s",k,l,m);
return 0;
}
output: prac c
stop cprac c
nice cstop cprac c
但是当我将大小从 6 更改为 7 时,这不会发生。
#include <stdio.h>
int main()
{
char k[]= "prac c";
char l[7]= "stop c"; //changing size to 7
char m[7]= "nice c"; //changing size to 7
printf("%s \n%s \n%s",k,l,m);
return 0;
}
output: prac c
stop c
nice c
解决方案
该字符串"stop c"
实际上是七个字符长,包括结尾的null-terminator。这适用于所有字符串。
如果您的数组中没有用于终止符的空间,则不会添加它,并且数组不再是通常所说的字符串。
使用这样的数组作为字符串将导致代码超出数组的范围并给您未定义的行为。
推荐阅读
- c# - 双引号消息的 Bot Framework 错误网关
- git - 如何为版本控制的 git commit 命令配置选项
- scala - Play Framework Scala 中的 SOAP API
- angular - switchMap Angular /
- transformation - 如何在颠簸变换中的数组中添加索引
- java - firebase url 在 firebase 中保存了错误的 url 地址
- excel - 错误处理 - 在哪里输入“退出子”?
- c - 如何在c中将表中的值相乘
- .htaccess - 使用部分 url 作为可获取变量,而不是通配符
- python-3.x - 检查 Pandas Dataframe 组是否在一列中有 2 个特定值并返回这些行