获取C中无符号字符数组的长度
Get length of array of unsigned chars in C
如何获取 unsigned char*
数组的数组长度?
这是我的数组:
unsigned char ot[] = { 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0, 0x0, 0x0, 0x0, 0x0 };
我试过这样使用 strlen()
:
int length = strlen((char*) ot);
它 return 我的长度是 11 直到第一个 0x0
,但是我的数组对此有何改变? (检查最后一个元素)
unsigned char ot[] = { 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0, 0x0, 0x0, 0x0, 0xa1 };
然后我仍然得到11个元素,我怎样才能得到整个数组的"real"长度?就像在某些 0x0
元素之后会有数据会怎样。
例如:
unsigned char* file_buffer = new unsigned char[BUFFER_SIZE];
fread(file_buffer,sizeof(unsigned char),BUFFER_SIZE,input_file)
最好的解决方案是什么?因为 fread()
的 return 值可能会有所不同,如果我正在读取文件的最后一块,并且如果文件中的某些数据是 0x0
怎么办?
How can I get length of array which is array of unsigned char*
?
根据您提供的示例,您正在尝试检索 array []
而不是 array *
的长度。这可以使用关键字 sizeof
(sizeof(ot)
).
来实现
然而,当涉及到指针时(比如你的 unsigned char *
),你需要事先知道大小,因为在它上面使用 sizeof
会 return 分配的大小指针本身,而不是该指针的实际内容大小。
unsigned char ot[] = {0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0, 0x0, 0x0, 0x0, 0x0};
int _length = strlen((char *) ot);
printf("%d\n", _length); // 11
int length = sizeof(ot) / sizeof(unsigned char);
printf("%d\n", length); // 16
// reason behind strlen behaves like this
if (0x0 == '[=10=]') {
printf("Yes\n");
}
strlen()
returns 找到 null terminator
时的字符串长度,即 '[=13=]'
。如果你 运行 代码,它会在最后打印 Yes
,意味着 0x0
实际上等同于 '[=13=]'
空终止符。
使用sizeof()
得到实际长度。
如何获取 unsigned char*
数组的数组长度?
这是我的数组:
unsigned char ot[] = { 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0, 0x0, 0x0, 0x0, 0x0 };
我试过这样使用 strlen()
:
int length = strlen((char*) ot);
它 return 我的长度是 11 直到第一个 0x0
,但是我的数组对此有何改变? (检查最后一个元素)
unsigned char ot[] = { 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0, 0x0, 0x0, 0x0, 0xa1 };
然后我仍然得到11个元素,我怎样才能得到整个数组的"real"长度?就像在某些 0x0
元素之后会有数据会怎样。
例如:
unsigned char* file_buffer = new unsigned char[BUFFER_SIZE];
fread(file_buffer,sizeof(unsigned char),BUFFER_SIZE,input_file)
最好的解决方案是什么?因为 fread()
的 return 值可能会有所不同,如果我正在读取文件的最后一块,并且如果文件中的某些数据是 0x0
怎么办?
How can I get length of array which is array of
unsigned char*
?
根据您提供的示例,您正在尝试检索 array []
而不是 array *
的长度。这可以使用关键字 sizeof
(sizeof(ot)
).
然而,当涉及到指针时(比如你的 unsigned char *
),你需要事先知道大小,因为在它上面使用 sizeof
会 return 分配的大小指针本身,而不是该指针的实际内容大小。
unsigned char ot[] = {0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0, 0x0, 0x0, 0x0, 0x0};
int _length = strlen((char *) ot);
printf("%d\n", _length); // 11
int length = sizeof(ot) / sizeof(unsigned char);
printf("%d\n", length); // 16
// reason behind strlen behaves like this
if (0x0 == '[=10=]') {
printf("Yes\n");
}
strlen()
returns 找到 null terminator
时的字符串长度,即 '[=13=]'
。如果你 运行 代码,它会在最后打印 Yes
,意味着 0x0
实际上等同于 '[=13=]'
空终止符。
使用sizeof()
得到实际长度。