0

I have some old code I inherited that I am maintaining and want to change as little as possible. It does not compile with newer compilers.

There is more to the code but basically the idea, I think, (regardless how bad) is to pass a void* to the start of a table of records of arbitrary record size. I do not want to make changes outside of this function since it gets ugly. I think I just want to cast to an unsigned char* and do the addition and then cast back to void* but I am having trouble figuring out the right casting etc.

Any suggestions?

Here is the original code:

foo(const void* recordArrayBasePtr ,ubin32 sizeOfStruct)
{
   void * recordPtr;
   int row = 9; //for example
   recordPtr = const_cast<void *>( recordArrayBasePtr ) + sizeOfStruct * row;
}
joemooney
  • 1,467
  • 1
  • 13
  • 17
  • You want const_cast< void* > as you have in your example, and reinterpret_cast< char* >. This is not enough, though, for your function's declaration is not having returned type, and there is no return at the end of your function. There is definitively something missing here. – Grzegorz Sep 24 '13 at 20:09
  • Why are you tagging this *C++*? Isn't this plain *C*? – Walter Sep 24 '13 at 20:37
  • This is C++ written by a C programmer. The solution from @jon did the trick: reinterpret_cast(const_cast( recordArrayBasePtr )) + sizeOfStruct * row; – joemooney Sep 24 '13 at 20:55

1 Answers1

0

You want to cast to char*, which is done with reinterpret_cast and not with const_cast. But considering that this is really C code, you can just as well use C-style casts which will be less of a hassle to write:

 recordPtr = (void*)((char*)recordArrayBasePtr + sizeofStruct * row);
Jon
  • 428,835
  • 81
  • 738
  • 806
  • recordPtr = static_cast( reinterpret_cast(recordArrayBasePtr) + m_haipeTableArray[tableId].sizeOfStruct * row); //this does not compile -- error: reinterpret_cast from type 'const void*' to type 'char*' casts away constness – joemooney Sep 24 '13 at 20:02
  • 1
    @joemooney: You need both casts there. But frankly I 'd use a C-style cast here. There's no point in putting nice C++ varnish over what is C code. – Jon Sep 24 '13 at 20:05
  • Any chance of putting that in C++ style casting for me? The compile will issue wanrings and I need to avoid warnings about old C style casts. – joemooney Sep 24 '13 at 20:05
  • @joemooney: `reinterpret_cast(const_cast( recordArrayBasePtr )) + sizeOfStruct * row;` Although I 'm not sure why you need to cast away the constness. – Jon Sep 24 '13 at 20:07
  • Excellent! That worked. I needed to cast away the constness because the pointer is passed down into another can of worms. – joemooney Sep 24 '13 at 20:13
  • `static_cast` to from `void*` is legal (or `const void *`). – Yakk - Adam Nevraumont Sep 24 '13 at 20:17