correct method to get the unsigned char pointer length

三世轮回 提交于 2019-12-02 04:11:34
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.

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";

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