C # pointers to create an int array?

The following C ++ program compiles and works 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 simple C # example I could do for this question:

 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 can I make a pointer?

+7
c ++ c pointers c #
source share
3 answers

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

In C ++, accessing an array is a short hand for manipulating a pointer. This is why the same thing:

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

However, this is not the case in C #. 5[test] not valid C # because System.Int32 does not have an indexer property.

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

 int[] test = new int[10]; 

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

If you really want to do this job, the closest you can do in 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; } } 

(Again, this is really weird C # - not what I would recommend ...)

+27
source share

You need to bind the array using the fixed keyword so that it is not moved by the GC:

 fixed (int* test = new int[10]) { // ... } 

However, unsafe code in C # is the exception rather than the rule. I would try translating C code to insecure C # code.

+5
source share

You need to learn the C # language. Despite its syntactic similarities to C / C ++, it, like Java, has a completely different approach.

In C #, objects behave by default as links. That is, you do not need to specify pointer references (&) and dereferencing syntax (*).

0
source share

All Articles