4

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

Atiq Rahman
  • 680
  • 6
  • 24
Amit
  • 33,847
  • 91
  • 226
  • 299

3 Answers3

15

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

QuantumMechanic
  • 13,795
  • 4
  • 45
  • 66
2
std::vector<unsigned char> buffer(1500);
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

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().

Felix Jones
  • 230
  • 3
  • 12