Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers in C# to make int array?

Tags:

c++

c

c#

pointers

The following C++ program compiles and runs as expected:

#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();
}

The closest C# simple example I could make for this question is:

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;
    }
}

So how do I make the pointer?

like image 482
y2k Avatar asked Mar 30 '10 16:03

y2k


1 Answers

C# is not C++ - don't expect the same things to work in C# that worked in C++. It's a different language, with some inspiration in the syntax.

In C++, array access is a short hand for pointer manipulation. That's why the following are the same:

test[5]
*(test+5)
*(5+test)
5[test]

However, this is not true in C#. 5[test] is not valid C#, since there is no indexer property on System.Int32.

In C#, you very rarely want to deal with pointers. You're better off just treating it as an int array directly:

int[] test = new int[10];

If you really do want to deal with pointer math for some reason, you need to flag your method unsafe, and put it into an fixed context. This would not be typical in C#, and is really probably something completely unnecessary.

If you really want to make this work, the closest you can do in C# would be:

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;
    }
}

(Again, this is really weird C# - not something I'd recommend...)

like image 101
Reed Copsey Avatar answered Oct 25 '22 22:10

Reed Copsey