how to reassign a fixed pointer

  • Thread starter Thread starter Schwammkopf
  • Start date Start date
S

Schwammkopf

Hi !

What i want to do in C++ is :

int a[] = new a[2];
a[0] = 0, a[1] = 0;

int* p = &a[0];

while (1) // any condition instead of 1
{
(*p)++;

if (p == &a[0])
p = &a[1];
else
p = &a[0];
}

How is this in C# possible ? I googled and found the unsafe / fixed
statements, but couldnt find
how to reassign the pointer to a new address.

C# :
unsafe {
fixed (int* p = &a[0]) {
while(1)
{
//how can i now reassign the p to another address ?
}
}
 
Here is the definition of the "fixed" key word from the SDK:

The fixed statement prevents the garbage collector from relocating a movable
variable.

Note that the variable is movable, and the fixed pointer only affects the
garbage collector. So, you would move the pointer in the same way.

--
HTH,

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net
 
How is this in C# possible ? I googled and found the unsafe / fixed
statements, but couldnt find
how to reassign the pointer to a new address.

The variable declared in the fixed statement is read-only. But you can
use it to initialize another variable and change that instead.

unsafe {
fixed (int* p = &a[0]) {
int* p2 = p;
while(true)
{
// Work with p2 here
}
}

That said, I fail to see the need for using pointers here at all. If
that's your actual code, it can easily be written to use "safe" code
instead. Something like

int i = 0;
while(<condition>)
{
p++;
i = ++i % 2;
}


Mattias
 
Thx.
No, its just a foo test code.

----- Original Message -----
From: "Mattias Sjögren" <[email protected]>
Newsgroups: microsoft.public.dotnet.languages.csharp
Sent: Thursday, April 05, 2007 10:42 PM
Subject: Re: how to reassign a fixed pointer

How is this in C# possible ? I googled and found the unsafe / fixed
statements, but couldnt find
how to reassign the pointer to a new address.

The variable declared in the fixed statement is read-only. But you can
use it to initialize another variable and change that instead.

unsafe {
fixed (int* p = &a[0]) {
int* p2 = p;
while(true)
{
// Work with p2 here
}
}

That said, I fail to see the need for using pointers here at all. If
that's your actual code, it can easily be written to use "safe" code
instead. Something like

int i = 0;
while(<condition>)
{
p++;
i = ++i % 2;
}


Mattias
 

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

Back
Top