unsafe?????????

W

wmhnq

private void button1_Click(object sender, EventArgs e)
{
unsafe
{
string str = "abcde";
fixed (char* pStr = str)
{
A a = new A(pStr);
a.change();
MessageBox.Show(str.ToString());
}
}
}
}

public class A
{
unsafe char* pStr = (char*)0;
public unsafe A(char* sss)
{
pStr =sss;
}

public unsafe void change()
{
*pStr = "fghijkl";//error,why??????

}
}
 
P

Peter Duniho

You might try spending a little more thought on your Subject: field for
your posts, so that it better describes the question you have, as well as
on the actual phrasing of your question in the post (for example, putting
more than just the code and "error,why").

Also, the Typographical Conservancy phoned, and they want to know why the
question mark population had a sudden decrease. I'll suggest that you can
help them avoid becoming endangered by not using so many, especially since
putting extra question marks in your post doesn't make the post any more
likely to be answered.

Now, all that said:

public class A
{
unsafe char* pStr = (char*)0;

public unsafe void change()
{
*pStr = "fghijkl";//error,why??????

}
}

You are assigning a string reference to a character. You didn't post the
compiler error, but I suspect it says exactly that: something about cannot
convert a string to a character.

You might prefer this line of code:

pStr = "fghijkl";

That should work better.

Pete
 
B

Brian Gideon

private void button1_Click(object sender, EventArgs e)
{
unsafe
{
string str = "abcde";
fixed (char* pStr = str)
{
A a = new A(pStr);
a.change();
MessageBox.Show(str.ToString());
}
}
}
}

public class A
{
unsafe char* pStr = (char*)0;
public unsafe A(char* sss)
{
pStr =sss;
}

public unsafe void change()
{
*pStr = "fghijkl";//error,why??????

}
}

I'm not understanding the need for unsafe code in your example.
 

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