1

In C++ I want to declare an array of pointers that are either unsigned char or unsigned short, depending on some input. So it would like either

unsigned char *data = new unsigned char[N];

or

unsigned short *data = new unsigned short[N];

What's the best way to go about this?

4
  • Is it an option two maintain two arrays and work with a pointer that will then be casted to the coresponding type? Commented Oct 13, 2014 at 18:02
  • "What's the best way to go about this?" make it a template. Commented Oct 13, 2014 at 18:03
  • How about allocating per input type, and always casting down to unsigned char*, and then go about reading values from that array based on the input (cast to short later if necessary) Commented Oct 13, 2014 at 18:05
  • You want array of pointers or array of unsigned chars/shorts? Your description is in conflict with code Commented Oct 13, 2014 at 18:07

1 Answer 1

3

"What's the best way to go about this?"

Make the context templated, e.g.

template<typename T, size_t N>
struct MyStuff {
    std::array<T,N> data;
}

or

template<typename T, size_t N>
struct MyStuff {
    std::vector<T> data;

    MyStuff() {
        data.resize(N);
    }
}

if you really need dynamic allocation

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.