SIZEOF VS STRLEN

编程入门 行业动态 更新时间:2024-10-23 09:36:44
本文介绍了SIZEOF VS STRLEN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 #include "stdio.h" #include "string.h" main() { char string[] = "october"; // october is 7 letters strcpy(string, "september"); // september is 9 letters printf("the size of %s is %d and the length is %d\n\n", string, sizeof(string), strlen(string)); return 0; }

输出:

九月的大小为8,长度是9

the size of september is 8 and the length is 9

是不是有什么毛病我的语法还是什么?

Is there something wrong with my syntax or what?

推荐答案

的sizeof 和的strlen()做不同的东西。在这种情况下,你的宣言

sizeof and strlen() do different things. In this case, your declaration

char string[] = "october";

是相同的

char string[8] = "october";

所以编译器可以告诉大家,字符串的大小为8它这样做是在编译时。

so the compiler can tell that the size of string is 8. It does this at compilation time.

然而,的strlen()计数的字符在运行时字符串中的数字。所以,你以后叫的strcpy(),字符串现在包含九。 的strlen()计数的人物和他们的发现9。需要注意的是你还没有分配足够的空间用于字符串举办九。这是不确定的行为。

However, strlen() counts the number of characters in the string at run time. So, after you call strcpy(), string now contains "september". strlen() counts the characters and finds 9 of them. Note that you have not allocated enough space for string to hold "september". This is undefined behaviour.

更多推荐

SIZEOF VS STRLEN

本文发布于:2023-11-29 23:13:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647921.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:SIZEOF   STRLEN

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!