请教一下

多年以后的 2020-06-01 08:17:32
#include<stdio.h>
#include<string.h>
int main()
{ char c[]="China";
char s[5]={'C','h','i','n','a'};
printf("%d\n",strlen(s));
printf("%d\n",sizeof(s));
return 0;
}
这个 程序的strlen输出是多少,为什么?
...全文
110 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qiu_shaofeng 2020-06-01
  • 打赏
  • 举报
回复
strlen的输出不确定。因为strlen以'\0'作为结束标志,字符数组s赋值满了且没有\0,发生数组越界,带来不确定的结果。
宾灬 2020-06-01
  • 打赏
  • 举报
回复
字符串和字符数组还是有点差别的.
#include<stdio.h>
#include<string.h>
int main()
{ 
	char c[] = "China";
	char s[5] = {'C','h','i','n','a'};
	printf("%d\n", strlen(s));
	printf("%d\n", sizeof(s));
	for(int i = 0; i < 10; i++){
		printf("%c, %p\n", s[i], &s[i]);
	}
 	return 0;
}
5250 2020-06-01
  • 打赏
  • 举报
回复
你的S定义的有问题 字符串数组要以\0结尾 你定义的S 5个字节 但是又输入了5个值 程序想读取\0读取到s[5]的位置了 s[5]恰巧又是C[]的数组,所以你的strlen(s)不是5 而是10

69,381

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧