问题描述
我正在使用strlen函数来获取无符号字符指针的长度。但是VS编译器会发出以下警告。
unsigned char myString [] =这是我的字符串;
unsigned char * tmpBuffer =& myString [0];
size_t size = strlen(tmpBuffer);
警告C4057:功能: const char *在间接寻址上与 unsigned char *略有不同的基本类型有所不同
那么获取无符号字符指针大小以消除警告的正确方法是什么。
使用 strlen
是O(N)解决O(1)问题的方法!
在编译时知道数组的大小。使用习惯用法 sizeof(myString)
。这是包括 NUL终止符的长度,因此将比 strlen
结果大1。
当然,如果数组对指针类型进行了衰减,则不能使用 sizeof
来获取长度。在这种情况下,可以使用强制转换为 const char *
的编译器警告:
size_t size = strlen((const char *)tmpBuffer);
请注意,计数中不包括Nstrong终止符。 / p> 由于代码中的古怪之处,因此需要强制转换。字符串文字在C中为 I am using strlen function to get the length of unsigned char pointer. But VS compiler throws the following warning. So what is the proper way to get unsigned char pointer size to get rid of the warning. Using The size of an array is known at compile time. Use the idiom Of course, you can't use noting that the NUL-terminator is not included in the count. The cast is required due to an oddity further back in your code. String literals are of 这篇关于获取无符号字符指针长度的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
const char []
,不是 const unsigned char []
。即使您平台上的 char
是 unsigned
, char
和未签名字符
仍然是不同的类型。如果代码段中的第一行是
const char myString [] =这是我的字符串,那会更好。
unsigned char myString[] = "This is my string";
unsigned char* tmpBuffer = &myString[0];
size_t size = strlen(tmpBuffer);
warning C4057: 'function' : 'const char *' differs in indirection to slightly different base types from 'unsigned char *'
strlen
is an O(N) solution to an O(1) problem!sizeof(myString)
. This is the length including the NUL-terminator, so will be 1 greater than the strlen
result.sizeof
to obtain the length if the array has decayed to a pointer type. In which case, you can obviate the compiler warning by using a cast to const char*
:size_t size = strlen((const char*)tmpBuffer);
const char[]
in C, not const unsigned char[]
. Even if char
is unsigned
on your platform, char
and unsigned char
are still distinct types. It would be better if the first line in your snippet wasconst char myString[] = "This is my string";