Question

I'd like to cast a const unsigned int* array into an int* array. static_cast and const_cast, however, fail.

const unsigned int* getArray()
{
  static unsigned int a[3];
  a[0] = 0;
  a[1] = 1;
  a[2] = 2;
  return a;
}
int main()
{
  const unsigned int * a = getArray();
  const_cast<int*>(a); // fail
  static_cast<int*>(a); // fail
}
Was it helpful?

Solution

  1. const_cast can't change the type, just the constness.
  2. static_cast can't take away the const, nor can it change between those pointer types.

What it looks like you want is:

int *b = reinterpret_cast<int *>(const_cast<unsigned int *>(a));

You can also just use a C-style cast in this case:

int *b = (int *)a;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top