Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper Way To Initialize Unsigned Char*

Tags:

c++

c

char

unsigned

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

like image 691
Brian Avatar asked Feb 02 '11 14:02

Brian


People also ask

How do I initialize an unsigned char?

unsigned char ch = 'a'; Initializing an unsigned char: Here we try to insert a char in the unsigned char variable with the help of ASCII value. So the ASCII value 97 will be converted to a character value, i.e. 'a' and it will be inserted in unsigned char.

What is a char * in C?

The abbreviation char is used as a reserved keyword in some programming languages, such as C, C++, C#, and Java. It is short for character, which is a data type that holds one character (letter, number, etc.) of data. For example, the value of a char variable could be any one-character value, such as 'A', '4', or '#'.

What is unsigned char pointer in C?

In C, unsigned char is the only type guaranteed to have no trapping values, and which guarantees copying will result in an exact bitwise image. (C++ extends this guarantee to char as well.) For this reason, it is traditionally used for "raw memory" (e.g. the semantics of memcpy are defined in terms of unsigned char ).

How do you declare an unsigned char in C++?

unsigned char ch = 'n'; Both of the Signed and Unsigned char, they are of 8-bits. So for signed char it can store value from -128 to +127, and the unsigned char will store 0 to 255. The basic ASCII values are in range 0 to 127.


2 Answers

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);
like image 134
Dmitry Avatar answered Sep 28 '22 09:09

Dmitry


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.

like image 44
Karl Bielefeldt Avatar answered Sep 28 '22 08:09

Karl Bielefeldt