Proper Way To Initialize Unsigned Char*

Brian picture Brian · Feb 2, 2011 · Viewed 74.9k times · Source

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)); ?

Answer

Dmitry picture Dmitry · Feb 2, 2011

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);