1

Consider a 2D, rectangular array. Say:

int[,] values = new int[len1, len2];

How can you iterate through all of its values in unsafe code?

1 Answer 1

2

The following works in an unsafe context.

fixed (int* baseOffset = values)
{
    var offset = baseOffset;
    var count = len1 * len2;
    for (int i = 0; i < count; i++)
    {
        int value = *offset;
        // Do whatever you need to do here
        offset++;
    }
}

Note that to get a pointer to the first item in an array, the types must match. So if you have a byte* which you want to treat as ushort*, you cannot cast the pointer within the fixed statement's parentheses, although you can do this within the block.

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

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.