When to use unsigned char pointer

后端 未结 4 1447
盖世英雄少女心
盖世英雄少女心 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:54

    You are actually looking for pointer arithmetic:

    unsigned char* bytes = (unsigned char*)ptr;
    for(int i = 0; i < size; i++)
        // work with bytes[i]
    

    In this example, bytes[i] is equal to *(bytes + i) and it is used to access the memory on the address: bytes + (i* sizeof(*bytes)). In other words: If you have int* intPtr and you try to access intPtr[1], you are actually accessing the integer stored at bytes: 4 to 7:

    0  1  2  3
    4  5  6  7 <-- 
    

    The size of type your pointer points to affects where it points after it is incremented / decremented. So if you want to iterate your data byte by byte, you need to have a pointer to type of size 1 byte (that's why unsigned char*).


    unsigned char is usually used for holding binary data where 0 is valid value and still part of your data. While working with "naked" unsigned char* you'll probably have to hold the length of your buffer.

    char is usually used for holding characters representing string and 0 is equal to '\0' (terminating character). If your buffer of characters is always terminated with '\0', you don't need to know it's length because terminating character exactly specifies the end of your data.

    Note that in both of these cases it's better to use some object that hides the internal representation of your data and will take care of memory management for you (see RAII idiom). So it's much better idea to use either std::vector (for binary data) or std::string (for string).

提交回复
热议问题