Is the following code correct inside a method?
int[] a = { 1, 2, 3, 4, 5 };
unsafe
{
fixed (int* p = &a[0])
{
p[1] = 3;
}
}
It has no errors but since a[0]
is fixed and a[1]
is not fixed explicitly, there may be some GC memory move for a[1]
.
How about this one?:
int[] a = { 1, 2, 3, 4, 5 };
unsafe
{
fixed (int* p = &a[1])
{
p[0] = 3;
}
}
Both the following assigns the address of the first element in array arr to pointer p.
fixed (double* p = arr)
is the same as
fixed (double* p = &arr[0])
in your case you assign the second element to a pointer
fixed (double* p = &arr[1])
In any case the array is pinned and protected from moving.