How to pass int * to a function that has a parameter of type int []?

How do you pass int a pointer to a function with a parameter of type int []? I need to pass pointer data from below code:

char* data = stackalloc char[123];

      

to a function with an int [] parameter.

foo(char [])

      

Next question:

How is int [] represented in C #? This is the same as in C ++ (pointer?)

+3


source to share


2 answers


Don't use the code unsafe

unless you have a good reason.

In any case, you can only use and manipulate pointers in code unsafe

. Your method Foo

accepts int[]

, not int*

, not char*

, not void*

. int[]

safe and verifiable - char*

no. You simply cannot pass a pointer, much less a pointer of a different type.

I am assuming that you are just confused about how C # works and you are trying to write C code in C #. If you want to work with an integer array, work with an integer array. If you want to work with char array use char array.

Arrays are a real type in C #, as opposed to the syntactic sugar of C - which means that they are much easier to work with, but it also means that they behave very differently than C. Similarly, you shouldn't really use stackalloc

if this is necessary - leave memory management running time, 99% of the time. Just think of these hacks when you've identified that code as a bottleneck, and even then only if the performance improvements (if any) are worth it.

So yes, working with arrays is as simple as it is in C #:



var integerArray = new int[] { 1, 2, 3 };
var charArray = new char[] { 'a', 'b', 'c' };

MethodTakingIntArray(integerArray);
MethodTakingCharArray(charArray);

      

If you need to stackalloc

(again, you really shouldn't, most of the time), all methods that handle that pointer should be unsafe

, and they should take a pointer argument:

private unsafe void HandleArray(int* array)
{
  // Do whatever
}

      

The reason is simple: the code is unsafe

not validated by the runtime, and pointers are not arrays. While you can do integerArray.Length

, there is no such thing on a pointer (obviously) - it's a completely different type.

Another warning: char

- this is not the same as in C / C ++. If you need a byte array, use byte[]

- char

is actually a unicode character and should not be used for non-character data.

+3


source


Read this: https://msdn.microsoft.com/en-us/library/4d43ts61(v=vs.90).aspx

Since arrays are reference types, when you pass an array to a function, you are passing a reference (or pointer) to the array.

You pass it just like this:



int[] arr = {1, 2, 3};
foo(arr);

      

And this is how you create a char array in C #:

char[] data = new char[123];

      

+1


source







All Articles