0

I was wondering if casting here is the best solution:

This is the function prototype:

void function(unsigned char * data)

This is how I intend to use it (nSize is read from):

unsigned int nSize = 15;

function( (unsigned char*) &nSize);
Paul R
  • 208,748
  • 37
  • 389
  • 560
tzippy
  • 6,458
  • 30
  • 82
  • 151
  • 5
    With the (very limited) information in the question, the answer can only be: Yes, you need to cast. The bigger question is *why* you need to pass a pointer to an integer to a function expecting a pointer to a character? – Some programmer dude Jun 05 '13 at 07:34
  • 3
    What is the motivation for using incompatible pointers like this ? – Paul R Jun 05 '13 at 07:34
  • 1
    You can also define function as function(void * data), and cast type inside. BTW what result you're expecting? – aisbaa Jun 05 '13 at 07:35
  • It is never good to make casts like that (unless you want to see what's going to happen). But, as already stated, we need more information about what you want to achieve to help you. – Anton Guryanov Jun 05 '13 at 07:37
  • 2
    I think this cannot be answered correctly without knowing the expectation - what you do with the data in this function. This would compile for sure. – Manoj Awasthi Jun 05 '13 at 07:38
  • I don't have influence on `function()` and the type of `nSize` – tzippy Jun 05 '13 at 07:42
  • I wonder what will happen if, say, `uint` is 16-bit variable and `uchar` is 8-bit (just proposal). Function will read just first 8 bits from `nSize`, that will be 00000000 in that case. Am i wrong? – SpongeBobFan Jun 05 '13 at 09:21

2 Answers2

1

Assuming the function prototype is set in stone and nSize has to be an int, yes that looks right to me.

vdbuilder
  • 12,254
  • 2
  • 25
  • 29
1

Yes, in your case, cast seems necessary.

Note that using C++-style named cast is preferred than the C-style cast. In your case, reinterpret_cast is the right choice. Note that this is a dangerous behavior, see here for detail.

function(reinterpret_cast<unsigned char*>&nSize);
Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294