简体   繁体   中英

visual c++: how to pass pointer to array as parameter?

The code below shown is in visual c++

array<Byte>^ b = gcnew array <Byte> (filesize);
fs->Read(b,0,b->Length);
unsigned char *pb;
pb=(byte*)malloc(b->Length);    //pb is unmanaged here.

for(int i=0;i<b->Length;i++)
{
     *(pb+i)=InverseByte(b+i);
}

I want to call the function below to reverse each byte. How can I do this? I want to do inverse of each byte of managed array b, and put it in the unmanaged array b.

unsigned char InverseByte(unsigned char* PbByte)
{
    //something;
}

Fix the declaration of InverseByte:

unsigned char InverseByte(unsigned char value)

So you can then use it like this:

for (int i=0; i < b->Length; i++)
{
    pb[i] = InverseByte(b[i]);
}

You mean bitwise negation I presume.

unsigned char InverseByte(unsigned char c)
{
    return ~c;
}

Note that I changed the parameter to pass by value rather than passing a pointer to the value.

I also fail to see why you are using pointer arithmetic instead of indexing. That just makes your code harder to read. The loop should be written like this:

for(int i=0;i<b->Length;i++)
{      
    pb[i] = InverseByte(b[i]);
}
unsigned char InverseByte(unsigned char c)
{
    return (c>>7)|((c&64)>>5)|((c&32)>>3)|((c&16)>>1)|((c&8)<<1)|((c&4)<<3)|((c&2)<<5)|((c&1)<<7);
}

From the comments it's clear you are reversing the bytes (ie reordering them front-to-back) rather than inverting (ie subtracting a variable from its maximum value) or negating (ie flipping 1's and 0's), so should name the function accordingly.

Here's a neat little snippet from Seander's bithacks:

   unsigned int v;     // input bits to be reversed
   unsigned int r = v; // r will be reversed bits of v; first get LSB of v
   int s = sizeof(v) * CHAR_BIT - 1; // extra shift needed at end

   for (v >>= 1; v; v >>= 1)
   {   
       r <<= 1;
       r |= v & 1;
       s--;
   }

   r <<= s; // shift when v's highest bits are zero
   return r;

If you combine Hans Passant's answer with this, you should have all the pieces to put together your function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM