温馨提示×

c#二维数组指针如何传参数

c#
小亿
83
2024-04-18 17:28:13
栏目: 编程语言

在C#中,二维数组其实是一个以数组为元素的数组,因此可以使用指针来传递二维数组参数。以下是一个示例代码:

using System;

class Program
{
    static void Main()
    {
        int[,] arr = new int[3, 3] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

        PrintArray(arr);
    }

    static void PrintArray(int[,] arr)
    {
        unsafe
        {
            fixed (int* p = &arr[0, 0])
            {
                for (int i = 0; i < arr.GetLength(0); i++)
                {
                    for (int j = 0; j < arr.GetLength(1); j++)
                    {
                        Console.Write(*(p + i * arr.GetLength(1) + j) + " ");
                    }
                    Console.WriteLine();
                }
            }
        }
    }
}

在上面的示例中,我们定义了一个二维数组 arr,然后通过 fixed 关键字将其指针 p 固定在内存中。然后通过指针的算术运算访问二维数组的元素,并打印出数组的内容。

需要注意的是,在使用指针操作数组时,需要在代码中添加 unsafe 关键字,因为这样的代码是不安全的,可能会导致内存访问越界等问题。

0