How to initialize unsigned char pointer

19,050

Solution 1

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

Solution 2

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

Solution 3

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

Share:
19,050
Amit
Author by

Amit

Updated on June 09, 2022

Comments

  • Amit
    Amit almost 2 years

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