Amit
Amit

Reputation: 34745

How to initialize unsigned char pointer

I want to initialize an unsigned char * buffer of length 1500 so that I can store values in it from some other sources.

Upvotes: 4

Views: 22201

Answers (3)

Felix Jones
Felix Jones

Reputation: 330

The C way of doing this is

unsigned char * buffer = ( unsigned char * )malloc( 1500 * sizeof( unsigned char ) );

If you want to initialise without junk data created from previous pointers, use calloc, this will initialise the buffer with character 0.

The ( unsigned char * ) in front of malloc is just to type cast it, some compilers complain if this isn't done.

Remember to call free() or delete() when you're done with the pointer if you're using C or C++ respectively, as you're in C++ you can use delete().

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490178

std::vector<unsigned char> buffer(1500);

Upvotes: 2

QuantumMechanic
QuantumMechanic

Reputation: 13946

If you want it on the heap,

unsigned char* buffer = new unsigned char[1500];

if you want it on the stack,

unsigned char buffer[1500];

Upvotes: 15

Related Questions