Hi @Adel , Welcome to Microsoft Q&A.
'Span<TSpan<T> objects are composed of a pointer to the start of the memory block and an integer representing the length of the memory block, which means they can only wrap contiguous memory blocks.
if you fix the first element of the Span, the rest of the memory block which is wrapped by the Span is also fixed. But it's unsafe. You have to handle it properly.
// See https://aka.ms/new-console-template for more information
using System.Runtime.CompilerServices;
int[] arr = new int[10];
Span<int> span = new Span<int>(arr);
Console.WriteLine("Before filling:");
PrintArray(arr);
// Call the Fill method to fill the Span with a value of 1.
Fill(span, 1);
Console.WriteLine("After filling:");
PrintArray(arr);
static void Fill(Span<int> sp, int v)
{
int n = sp.Length;
unsafe
{
fixed (int* ptrSP = &sp[0])
{
int* ptr = ptrSP;
while (n-- > 0)
{
*ptr++ = v;
}
}
for (int i = 0; i < sp.Length; i++)
{
Console.WriteLine((int)Unsafe.AsPointer(ref sp[i]));
}
}
}
static void PrintArray(int[] arr)
{
unsafe
{
fixed (int* ptr = arr)
{
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + " ");
Console.WriteLine((int)(ptr + i));
}
}
}
Console.WriteLine();
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.