单字符的Strlen函数行为

编程入门 行业动态 更新时间:2024-10-26 17:30:45
本文介绍了单字符的Strlen函数行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我的代码:

void func(char c) { char * ptr = &c; size_t len = strlen(ptr); printf("len - %d\n", len); }

len 始终列为1。

strlen(..)确定 char 数组,方法是在其末尾找到空字符( \0 )。在这里, ptr 仅使用单个字符的地址( c )进行初始化。 c 不包含任何空字符。 ptr 如何获取长度?

strlen(..) determines the length of a char array by finding the null character (\0) at the end of it. Here ptr is initialized with just the address of a single character (c). c does not contain any null characters. How does ptr get the length?

推荐答案

您不能使用 strlen()指向不指向以空值结尾的数组的指针。它会调用未定义的行为。

You cannot use strlen() on a pointer that does not point to a null-terminated array. It invokes undefined behavior.

一次

FWIW, strlen()返回类型 size_t ,因此您应使用%zu 格式说明符来打印结果。

FWIW, strlen() returns a type size_t, so you should use %zu format specifier to print the result.

更多推荐

单字符的Strlen函数行为

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

发布评论

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

>www.elefans.com

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