1

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;
    }
}

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

The variable you pin is a. It's managed as a single allocation. Individual array elements will never be relocated, only the array as a whole.

Depending on your needs, you might consider using stackalloc instead to allocate memory on the stack rather than on the heap. Variables on the stack are not subject to GC and therefore do not need to be pinned.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.