Pointer, is this ok?

  • Thread starter Thread starter Michael C
  • Start date Start date
M

Michael C

I've got a pointer to a byte and want to set the byte it points to to zero
as well as the three bytes after. I could do this

dstPtr[0] = 0;
dstPtr[1] = 0;
dstPtr[2] = 0;
dstPtr[3] = 0;

but can convert it to an int* first and just do

*(int*)dstPtr = 0;

is this correct and is it good practice? Is it the best way to do it?

Thanks,
Michael
 
You may have the wrong ng; this is c#... try c/c++ groups. An IntPtr
doesn't lend itself to this usage, although as it happens
System.Runtime.InteropServices.Marshal.ReadIntPtr(System.IntPtr) might
do the trick.

Marc
 
Marc,
You may have the wrong ng; this is c#... try c/c++ groups.

C# supports pointers too, you know.

Nothing wrong with casting to an int* first IMO.


Mattias
 
Marc Gravell said:
You may have the wrong ng; this is c#... try c/c++ groups. An IntPtr
doesn't lend itself to this usage, although as it happens
System.Runtime.InteropServices.Marshal.ReadIntPtr(System.IntPtr) might
do the trick.

That's not true. C# can work with pointers no problem. If you've got an
IntPtr you can write code like this

byte* ptr = (byte*) MyIntPtr;
*ptr = 5;
ptr ++;
etc

Michael
 
Yikes! I'm truly embarrassed to say that I had completely overlooked that
usage of pointers withing C#. Learn a new thing etc...

I guess I've just tried to avoid "unsafe" except where absolutely necessary,
limiting myself to the safe variations.

But yup, I'll take that on the chin. I was completely wrong.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top