about references and pointers

T

TonyJ

Hello!

You can write int[] vektor = new int[5];
This array will be stored on the heap and you will have a reference(vektor)
to this array. As long as you keep a reference to this array will GC never
remove
this array.
If you for example set vektor = null then you give the GC permission to
remove this array.

Now to my question which is about unsafe code which is pointer

If you write int * vektor = new int[5];
This will not compile becuse array is reference types.
You must pinning is this way.
(fixed) {int * vektor = new int[5]; }

But I can't understand why you must use (fixed) ?
I mean when you use reference types you never have to use fixed only when
use
unsafe code like pointers.

I mean a reference is only a hidden pointer.

//Tony
 
A

Alberto Poblacion

TonyJ said:
You can write int[] vektor = new int[5];
This array will be stored on the heap and you will have a
reference(vektor)
to this array. As long as you keep a reference to this array will GC never
remove
this array.
If you for example set vektor = null then you give the GC permission to
remove this array.

Now to my question which is about unsafe code which is pointer

If you write int * vektor = new int[5];
This will not compile becuse array is reference types.
You must pinning is this way.
(fixed) {int * vektor = new int[5]; }

But I can't understand why you must use (fixed) ?
I mean when you use reference types you never have to use fixed only when
use
unsafe code like pointers.

I mean a reference is only a hidden pointer.

The problem is that the memory allocated to a reference type can move
around when the Garbage Collector runs. The GC will adjust references so
that they still "point" to their object after collecting memory. But if you
use a pointer and the memory moves, it would point to a "wrong" place.
That's why you write "fixed", in order to lock the memory to which the
pointer is pointing so that the GC doesn't relocate it.
 

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

Top