how to define a pointer to an array?

P

Peter Demeyer

I can't manage to define a simple pointer to an array.
The following C++ code doesn't work in C# (compiler error: "You can
only take the address of unfixed expression inside of a fixed statement
initializer")

Int32 *pointer;
int []array = new int[100];
pointer = &array[0];

Can anyone please instruct me how to do this properly in C#?
Thanks,
Peter
 
M

Mattias Sjögren

Peter,
Can anyone please instruct me how to do this properly in C#?

If you really have to do it:

unsafe {
fixed (int* pointer = array) {
// Do stuff here
}
}


Mattias
 
G

Guest

You can define a pointer to an array... but only within a limited area by
using the fixed statement
(http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrffixed.asp) ... in this case you would do it like this:

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

By using the fixed keyword, you are telling the CLR that you want to force
it not to move the data that the pointer is pointing at around in memory
(which is a real risk with managed code).

Be sure to note that the pointer is only usable within with in the statement
(ie between { and }) immediately following the fixed keyword, so you cannot
take this pointer with you... however it is still usable for things like
P/Invokes and some pointer arithmetic.

Brendan
 
J

Jon Skeet [C# MVP]

Peter Demeyer said:
I can't manage to define a simple pointer to an array.
The following C++ code doesn't work in C# (compiler error: "You can
only take the address of unfixed expression inside of a fixed statement
initializer")

Int32 *pointer;
int []array = new int[100];
pointer = &array[0];

Can anyone please instruct me how to do this properly in C#?

Others have given you the answer of how - could I ask *why* you need to
do this? It could well be that there's an answer to the problem you're
trying to tackle that doesn't require pointers.
 
P

Peter Demeyer

Thank you all very much!
I managed to do what I wanted with your help.
Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top