Home > Blockchain >  How to implement something like int*[] in C#?
How to implement something like int*[] in C#?

Time:01-10

In C/C , the type of array element can be int*. Can C# implement something like it? For example:

int main()
{
    int x = 1;
    int y = 2;
    int* a1[2];
    a1[0] = &x;
    a1[1] = &y;
    *a1[0] = 3;
    *a1[1] = 4;
    printf("%d\n", x);
    printf("%d\n", y);
}

CodePudding user response:

This is the closest you are going to get to this code

static class Program
{
    unsafe static void Main(string[] args)
    {
        int x = 1;
        int y = 2;

        var a1 = stackalloc int*[2];
        a1[0] = &x;
        a1[1] = &y;
        
        *a1[0] = 3;
        *a1[1] = 4;

        Console.WriteLine("{0}", x);
        Console.WriteLine("{0}", y);
    }
}

CodePudding user response:

int* a1[2];
...
*a1[0] = 3;
*a1[1] = 4;

This is more or less equal to the following C# code:

int[][] a1 = new int[2][];
...
a1[0][0] = 3;
a1[1][0] = 4;
int x = 1;
int y = 2;
...
a1[0] = &x;
a1[1] = &y;

If you want to use "pure .NET code" (not unsafe etc.), you might simulate a primitive variable using an array with a size of [1]. I often used that method when programming in Java (for example to simulate out or ref parameters that exist in C# but not in Java):

int[] x = new int[] { 1 }; // instead of int x = 1;
int[] y = new int[] { 2 }; // instead of int y = 2;
...
a1[0] = x;
a1[1] = y;

If you do this, you have to replace all occurrences of x by x[0], of course:

Console.WriteLine("x = "   x[0]); // instead of Console.WriteLine("x = "   x);
  •  Tags:  
  • Related