This is an easy one, I am sure, but I can't seem to find it on google.
If I have a function:
foo(int[] a) {}
and I want to call it with a subarray of an array:
for instance: myNums[3]+ (i.e. an array {4,5,6}), given myNums:
int[] myNums = { 1,2,3,4,5,6};
Of course, I don't want to create a new array of just those sub items. I certainly could just pass the array and the index, but then I would have to write all the function code with offsets...ugly.
So, how does one do this in C# (.NET 2.0)?
foo(&myNums[3]) is reporting unsafe.
foo(myNums[3]) won't work (it is passing just an int).
Do I need to map this to some kind of collection?
Passing the address of an array to a function is something not supported by C# out-of-the-box. Either you have to do it using unsafe method, the code will be C-like (though you need to compile with unsafe option). or you would have to code it the way managed code are ought to be, in this case, pass the offset.
public Form1()
{
InitializeComponent();
int[] a = { 4, 5, 6, 7, 8 };
unsafe
{
fixed (int* c = a)
{
SubArrayPointer(c + 3);
}
}
SubArray(a, 3);
}
unsafe void SubArrayPointer(int* d)
{
MessageBox.Show(string.Format("Using pointer, outputs 7 --> {0}", *d));
}
void SubArray(int[] d, int offset)
{
MessageBox.Show(string.Format("Using offset, outputs 7 --> {0}", d[offset]));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With