Connecting Tech Pros Worldwide Forums | Help | Site Map

Array pointers in C#

Newbie
 
Join Date: Oct 2009
Posts: 1
#1: Oct 7 '09
Hi guys

Im attempting to write conways Game of life and need to use a pointer and 2 arrays. The reason im using a pointer is hopefully to speed up the code rather than copying the array > processing it and copying it back.

I found this code in an old post on the forum but having never used pointers before im a little lost with what to do.

int []array = new int[100];
fixed(int* pointer = &array[0])
{
//use the pointer
}

my code will use two arrays, grid1 and grid2

thus I suspect my code should look like:

Cell [,]grid1 = new Cell[10,10];
Cell [,]grid2 = new Cell[10,10];
fixed(int* pointer = &grid1[0,0])
{
//use the pointer
}

So firstly is this line .....fixed(int* pointer = &Cell[0,0]) just saying basically the pointer called pointer refers to the array grid1[0,0] ?

And secondly how would I manipulate data in the array being pointed to?

Do i use pointer[0,0] etc as if it were a normal array?

Sorry for such a long post but I've never had to use pointers before and im finding a few posts on the topic a little confusing.

Anyways any help would be greatly apreciated, thanks

Familiar Sight
 
Join Date: Jul 2009
Location: Calgary, Alberta, Canada
Posts: 227
#2: Oct 7 '09

re: Array pointers in C#


I'm reasonably sure anything except simple value types are passed by reference already in C#. Simple value types are things like int, bool, double, etc...

So I'm fairly sure that your arrays are already being passed by reference. Still, you can explicitly state this by adding the ref keyword to your parameter declaration..

Expand|Select|Wrap|Line Numbers
  1. public void ManipulateArray(ref int[] intArray)
  2. {
  3.   ...
  4. }
As for how you manipulate it, treat it like any other array.
Reply

Tags
array, pointer