用C#指示生成int数组?

y2k*_*y2k 8 c c# c++ pointers

以下C++程序按预期编译和运行:

#include <stdio.h>

int main(int argc, char* argv[])
{
    int* test = new int[10];

    for (int i = 0; i < 10; i++)
            test[i] = i * 10;

    printf("%d \n", test[5]); // 50
    printf("%d \n", 5[test]); // 50

    return getchar();
}
Run Code Online (Sandbox Code Playgroud)

我能为这个问题做出的最接近的C#简单示例是:

using System;

class Program
{
    unsafe static int Main(string[] args)
    {
        // error CS0029: Cannot implicitly convert type 'int[]' to 'int*'
        int* test = new int[10];

        for (int i = 0; i < 10; i++)
            test[i] = i * 10;

        Console.WriteLine(test[5]); // 50
        Console.WriteLine(5[test]); // Error

        return (int)Console.ReadKey().Key;
    }
}
Run Code Online (Sandbox Code Playgroud)

那么如何制作指针呢?

Ree*_*sey 30

C#不是C++ - 不要指望在C#中使用相同的东西工作.它是一种不同的语言,在语法上有一些灵感.

在C++中,数组访问是指针操作的简写.这就是为什么以下是相同的:

test[5]
*(test+5)
*(5+test)
5[test]
Run Code Online (Sandbox Code Playgroud)

但是,在C#中并非如此. 5[test]是无效的C#,因为System.Int32上没有索引器属性.

在C#中,你很少想要处理指针.你最好直接将它作为一个int数组处理:

int[] test = new int[10];
Run Code Online (Sandbox Code Playgroud)

如果您确实想要出于某种原因处理指针数学,则需要标记您的方法不安全,并将其置于固定的上下文中.这在C#中并不典型,而且实际上可能完全没有必要.

如果你真的想要做这个工作,那么你在C#中最接近的将是:

using System;

class Program
{
    unsafe static int Main(string[] args)
    {
        fixed (int* test = new int[10])
        {

            for (int i = 0; i < 10; i++)
                test[i] = i * 10;

            Console.WriteLine(test[5]); // 50
            Console.WriteLine(*(5+test)); // Works with this syntax
        }

        return (int)Console.ReadKey().Key;
    }
}
Run Code Online (Sandbox Code Playgroud)

(再次,这真是奇怪的C# - 不是我推荐的......)


dtb*_*dtb 5

您需要使用fixed关键字固定数组,以便GC不会移动它:

fixed (int* test = new int[10])
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

但是,C#中的不安全代码不是规则的例外.我试着将你的C代码翻译成非不安全的C#代码.

  • 注意:使用固定的变量不应该有充分的理由,因为它会使GC的工作变得更难......即使你不使用所有内存(内存碎片整理),你也可能会耗尽内存. (2认同)