Proper Way To Initialize Unsigned Char*

80,882

Solution 1

The second method will leave you with a null pointer. Note that you aren't declaring any space for a buffer here, you're declaring a pointer to a buffer that must be created elsewhere. If you initialize it to "", that will make the pointer point to a static buffer with exactly one byte—the null terminator. If you want a buffer you can write characters into later, use Fred's array suggestion or something like malloc.

Solution 2

To "properly" initialize a pointer (unsigned char * as in your example), you need to do just a simple

unsigned char *tempBuffer = NULL;

If you want to initialize an array of unsigned chars, you can do either of following things:

unsigned char *tempBuffer = new unsigned char[1024]();
// and do not forget to delete it later
delete[] tempBuffer;

or

unsigned char tempBuffer[1024] = {};

I would also recommend to take a look at std::vector<unsigned char>, which you can initialize like this:

std::vector<unsigned char> tempBuffer(1024, 0);

Solution 3

As it's a pointer, you either want to initialize it to NULL first like this:

unsigned char* tempBuffer = NULL;
unsigned char* tempBuffer = 0;

or assign an address of a variable, like so:

unsigned char c = 'c';

unsigned char* tempBuffer = &c;

EDIT: If you wish to assign a string, this can be done as follows:

unsigned char myString [] = "This is my string";
unsigned char* tmpBuffer = &myString[0];

Solution 4

If you know the size of the buffer at compile time:

unsigned char buffer[SIZE] = {0};

For dynamically allocated buffers (buffers allocated during run-time or on the heap):

1.Prefer the new operator:

unsigned char * buffer = 0;  // Pointer to a buffer, buffer not allocated.
buffer = new unsigned char [runtime_size];

2.Many solutions to "initialize" or fill with a simple value:

std::fill(buffer, buffer + runtime_size, 0); // Prefer to use STL
memset(buffer, 0, runtime_size);
for (i = 0; i < runtime_size; ++i) *buffer++ = 0;  // Using a loop

3.The C language side provides allocation and initialization with one call.
However, the function does not call the object's constructors:

buffer = calloc(runtime_size, sizeof(unsigned char))

Note that this also sets all bits in the buffer to zero; you don't get a choice in the initial value.

Solution 5

It depends on what you want to achieve (e.g. do you ever want to modify the string). See e.g. http://c-faq.com/charstring/index.html for more details.

Note that if you declare a pointer to a string literal, it should be const, i.e.:

const unsigned char *tempBuffer = "";
Share:
80,882
Brian
Author by

Brian

Updated on July 09, 2022

Comments

  • Brian
    Brian almost 2 years

    What is the proper way to initialize unsigned char*? I am currently doing this:

    unsigned char* tempBuffer;
    tempBuffer = "";
    

    Or should I be using memset(tempBuffer, 0, sizeof(tempBuffer)); ?