何时使用unsigned char指针 [英] When to use unsigned char pointer
问题描述
unsigned char
指针的用途是什么?我已经在许多地方看到指针是类型转换为指向 unsinged char
的指针为什么我们这样做?
What is the use of unsigned char
pointers? I have seen it at many places that pointer is type cast to pointer to unsinged char
Why do we do so?
我们收到一个指向 int
的指针,然后将它转换为 unsigned char *
。但是如果我们尝试使用cout在该数组中打印元素,它不打印任何东西。为什么?我不明白。
We receive a pointer to int
and then type cast it to unsigned char*
. But if we try to print element in that array using cout it does not print anything. why? I do not understand. I am new to c++.
编辑下面的示例代码
int Stash::add(void* element)
{
if(next >= quantity)
// Enough space left?
inflate(increment);
// Copy element into storage, starting at next empty space:
int startBytes = next * size;
unsigned char* e = (unsigned char*)element;
for(int i = 0; i < size; i++)
storage[startBytes + i] = e[i];
next++;
return(next - 1); // Index number
}
推荐答案
, unsigned char
是唯一保证没有捕获值的类型,并且保证复制将产生精确的逐位图像。因为这个原因,它传统上用于原始内存(例如 memcpy c的语义) / code>以
unsigned char
)定义。
In C, unsigned char
is the only type guaranteed to have no trapping values, and which guarantees copying will result in an exact bitwise image. (C++ extends this guarantee to char
as well.) For this reason, it is traditionally used for "raw memory" (e.g. the semantics of memcpy
are defined in terms of unsigned char
).
此外,一般用于位操作(&
, |
,> code>等)将被使用。
unsigned char
是最小的无符号整数类型,可以在操作使用按位运算的小值数组时使用。有时,它也被使用,因为在溢出的情况下需要模数行为,虽然这对于较大的类型(例如当计算哈希值时)更频繁。这两个原因一般适用于无符号类型; unsigned char
通常只会在需要减少内存使用时使用。
In addition, unsigned integral types in general are used when bitwise operations (&
, |
, >>
etc.) are going to be used. unsigned char
is the smallest unsigned integral type, and may be used when manipulating arrays of small values on which bitwise operations are used. Occasionally, it's also used because one needs the modulo behavior in case of overflow, although this is more frequent with larger types (e.g. when calculating a hash value). Both of these reasons apply to unsigned types in general; unsigned char
will normally only be used for them when there is a need to reduce memory use.
这篇关于何时使用unsigned char指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!