When to use unsigned char pointer

后端 未结 4 1445
盖世英雄少女心
盖世英雄少女心 2021-02-06 03:11

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?

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 03:55

    Unsigned char pointers are useful when you want to access the data byte by byte. For example, a function that copies data from one area to another could need this:

    void memcpy (unsigned char* dest, unsigned char* source, unsigned count)
    {
        for (unsigned i = 0; i < count; i++)
            dest[i] = source[i];
    }
    

    It also has to do with the fact that the byte is the smallest addressable unit of memory. If you want to read anything smaller than a byte from memory, you need to get the byte that contains that information, and then select the information using bit operations.

    You could very well copy the data in the above function using a int pointer, but that would copy chunks of 4 bytes, which may not be the correct behavior in some situations.

    Why nothing appears on the screen when you try to use cout, the most likely explanation is that the data starts with a zero character, which in C++ marks the end of a string of characters.

提交回复
热议问题