unsigned char
指针有什么用?我在许多地方看到将指针强制转换为unsigned char
指针的情况。我们为什么这样做?
我们收到一个指向int
的指针,然后将其类型转换为unsigned char*
。但是,如果我们尝试使用cout
打印该数组中的元素,则不会打印任何内容。为什么?我不理解。我是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 *
被用作字节级访问方法,以便访问变量或内存地址中的更正式类型。它有许多好处,其中包括免疫严格别名规则和标准保证对任何地址都具有对齐性。如果你对C语言比较熟悉,那么新学习C++应该不会太难。如果你是编程新手,我认为这可能是一个理解上的挑战。也许你有一些代码和想法需要提出问题? - WhozCraig