correct method to get the unsigned char pointer length

一笑奈何 提交于 2019-12-02 11:31:25

问题


I am using strlen function to get the length of unsigned char pointer. But VS compiler throws the following warning.

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 *'

So what is the proper way to get unsigned char pointer size to get rid of the warning.


回答1:


strlen((const char*)tmpBuffer);

Let you get rid of the note. Here you are typecasting it to the appropriate type that is being expected by the strlen()

From standard the prototype of the function is

size_t strlen(const char *s);

But here you were passing it of type unsigned char* that's why the complain.

Also if you are using it for simply storing strings as shown in example. You can use char without any problem.




回答2:


Using strlen is an O(N) solution to an O(1) problem!

The size of an array is known at compile time. Use the idiom sizeof(myString). This is the length including the NUL-terminator, so will be 1 greater than the strlen result.

Of course, you can't use 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);

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[] 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 was

const char myString[] = "This is my string";



回答3:


You should be able to explicitly cast to a char* to get rid of that warning:

size_t size = strlen((char*)tmpBuffer);

Alternately, since tmpBuffer is an array declared in the scope you're in, you can use the sizeof operator:

size_t size = sizeof(myString) / sizeof(myString[0]) - 1;


来源:https://stackoverflow.com/questions/47808588/correct-method-to-get-the-unsigned-char-pointer-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!