1

If I need to treat something as an unsigned char array, is this the correct way for a function:

int main() {
    int i = 500;
    f(&i);
}

void f(void *ptr) {
    unsigned char *byteptr = static_cast<unsigned char *>(ptr);
    ...
}

What if I don't have a function? Should I use two static_cast, first to void * and then to unsigned char *?

1
  • 6
    What are you actually trying to do? Commented Nov 28, 2013 at 17:08

1 Answer 1

2

To cast a pointer to your int variable to an unrelated type like unsigned char, you will need to use reinterpret_cast:

unsigned char *byteptr = reinterpret_cast<unsigned char *>(&i);

But I echo the commenter's question: what are you actually trying to do? It seems unlikely that anything useful can come of casting int * to unsigned char * like this.

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

6 Comments

That shall be my new name. "The Commenter". :D
C++ objects are made up of bytes, which can be accessed via character types. You can copy those bytes around, and sometimes even copy them back to the original object. This is explicitly permitted by the standard.
@n.m.: Explicitly? Chapter and verse, please.
@LightnessRacesinOrbit: 3.9.2
@potrzebie No it isn’t. A reinterpret_cast between (unsigned) char* and the original object type is explicitly allowed by the standard. By contrast, I’m actually not sure if your original code is – as far as I remember you may only cast between void* and the original type, your code thus violates strict aliasing rules.
|

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.