本文介绍了单字符的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函数行为
发布评论