-1

Hey Peeps,

Am currently working on porting some old C Library to C# but have a bit of trouble understanding a certain piece of Code containing Pointers.
Am not the best when it comes to C so i might be lacking some understanding.

Heres a simplified version of what im Looking at:

unsigned int block[2];

// --- inside a function

unsigned int *block;       // only got access to this pointer not the array
unsigned long left, right;

// some math


*block++ = right;  // these lines are the important bit i dont quite get
*block = left;

now...

What I think i got so far is:

  • The first line...
    • dereferences the pointer
    • sets its value to right
    • steps the pointer forward by 1
  • And the second line...
    • dereferences the pointer
    • sets its value to left

Now what i have trouble wrapping my head around is how the end result (blocks[]) looks.
(Sadly cant just debug it and take a peek bc I only have dont really know how id do that with a lib binary...)
Would be fairly simple if left and right were uints aswell but they are both ulongs so theres probably some sort of overwriting going on right?

Am a little confused / lost on this one... Maybe some of you with some better C knowledge can help me out ^^

RedCube
  • 25
  • 4
  • Is ```block``` ever initialized inside the function? – sj95126 Oct 07 '21 at 20:22
  • Hey @sj95126 should have probably mentioned that hehe, `block` is initialised before its handed to the function. @Barmar already gave me the answer i was looking for but still thanks for answering! ^^ – RedCube Oct 07 '21 at 20:26
  • I meant where you refer to ```unsigned int *block``` as "inside a function" - in that context, is ```block``` a parameter to the function, or a local variable? Just making sure the pointer has a valid value, or dereferencing it would be undefined behavior that might "happen" to work. But if Barmar has solved your problem, great! – sj95126 Oct 07 '21 at 20:30

1 Answers1

1

This is basically doing:

block[0] = (unsigned int) right;
block[1] = (unsigned int) left;

And casting unsigned long to unsigned int simply discards the excess high order bits.

Barmar
  • 741,623
  • 53
  • 500
  • 612