如何将数组的数组传递给 C# 中的函数?

How do you pass an array-of-arrays to a function in C#?

注意,这个问题具体是关于一个"array-of-arrays",不是多维数组,也不是锯齿状数组,而是一个固定大小的方形数组。在 C++ 中,这将是一个 "plain old array",但这个问题不是关于互操作的,只是普通的 C# 给出了一个 "Stack overflow",表明传递的数组在接收函数中最终为空。

构建普通数组似乎工作正常:

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };
int[][] lists = new int[][] {
    list1, list2, list3, list4
};

调用有问题的函数似乎都是安全的,正常的 C# 代码:

Solution solution();
Console.WriteLine(a.solution(lists));

现在,数组的大小当然不包含在信息中。这正是问题所在。但是这个 C# 的哪一部分是 "unsafe" ?我们没有为此设置关键字吗?

函数签名 int int[][] f(),在单独的 class:

public int solution(int[][] A){
  // 1) try to access A using A.Length, which doesn't turn out to have the right information
  // 2) get a segfault
  // 3) cry
  return A.Length;
}

问题是: "How do you pass an array-of-arrays into a C# function, such that the signature of Solution.solution doesn't need to change?"

我也很困惑我的代码,它肯定会检查 A.Length 和 A[0]。输入的长度,仍然是段错误。我原以为未明确标记 "unsafe" 的 C# 代码因此会是 "safe"。但我想 "safe" 并不意味着以上述方式传递的数组实际上到达了被调用的函数。

最终的目标是能够在本地进行 Codility 测试,无论我想要多少测试用例。

注意:完整的源代码,只有两个小文件,有一些不相关的代码(在解决方案 class 中),但是有一个 Makefile 和你需要的一切,就在这里:https://github.com/TamaHobbit/ActualSolution/blob/master/test_framework.cs

错误信息全文:

Stack overflow: IP: 0x41ed8564, fault addr: 0x7ffc3c548fe0
Stacktrace:
  at Solution.DFS (int,int,int) [0x00040] in <6d4ef1577c8c4e11a148ddbe545112a9>:0
  <...>
  at Solution.solution (int[][]) [0x00022] in <6d4ef1577c8c4e11a148ddbe545112a9>:0
  at TestFramework.Main () [0x00068] in <6d4ef1577c8c4e11a148ddbe545112a9>:0
  at (wrapper runtime-invoke) object.runtime_invoke_void (object,intptr,intptr,intptr) [0x0004c] in <a07d6bf484a54da2861691df910339b1>:0

你有一个数组数组。因此,在索引 0、1、2 和 3 处,您有一个包含 4 个项目的数组。具体来说,您有一个包含 4 个数组的数组。以下是获取它们大小的方法:

public static void Main()
{
    int[] list1 = new int[4] { 1, 2, 3, 4 };
    int[] list2 = new int[4] { 5, 6, 7, 8 };
    int[] list3 = new int[4] { 1, 3, 2, 1 };
    int[] list4 = new int[4] { 5, 4, 3, 2 };
    int[][] lists = new int[][] { list1, list2, list3, list4 };
    var size = GetSize(lists);

}

public static int GetSize(int[][] items)
{
    var arrAt0 = items[0].Length;
    var arrAt1 = items[1].Length;
    // Etc...

    return items.Length;
}

要从数组中取出一个项目,您可以这样做:

var lastItemInArray1 = lists[0][3];