Consider the following code in an unsafe context:
string mySentence = "Pointers in C#";
fixed (char* start = mySentence) // this is the line we're talking about
{
char* p = start;
do
{
Console.Write(*p);
}
while (*(++p) != '\0');
}
Console.ReadLine();
This works good.
According to http://msdn.microsoft.com/en-us/library/f58wzh21(v=VS.100).aspx I should be able to replace the line I marked with
fixed(char* start = &mySentence[0])
But unfortunately VS gives me the following error.
Cannot take the address of the given expression
Is the error on my side?
VS.NET 2010 Premium.
Is the error on my side?
No; the error is in the documentation you linked to. It states:
fixed (char* p = str) { /*...*/ } // equivalent to p = &str[0]
The comment is incorrect; as you correctly note, it is not legal to take the address of the interior of a string. It is only legal to take the address of the interior of an array.
The legal initializers for a fixed statement are:
&
applied to a variable reference. str[0]
is not a variable reference, because first, string elements are not variables, and second, because this is a call to an indexing function, not a reference to a variable. Nor is it an array, a string, or a fixed-size buffer, so it should not be legal.
I'll have a chat with the documentation manager and we'll see if we can get this fixed in a later revision of the documentation. Thanks for bringing it to my attention.
UPDATE: I have spoken to one of the documentation managers and they have informed me that we have just passed the deadline for the next scheduled revision of the documentation. The proposed change will go in the queue for the revision after next.
This doesn't work because you're trying to access a string. If you change your code to:
char[] mySentence = "Pointers in C#".ToCharArray();
fixed (char* start = &mySentence[0])
{
char* p = start;
do
{
Console.Write(*p);
}
while (*(++p) != '\0');
}
Console.ReadLine();
everything will work fine.
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