Consider the following code in an unsafe context:
string mySentence = \"Pointers in C#\";
fixed (char* start = mySentence) // this is the line we\'re talkin
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.
mySentence[0] returns a readonly single character, you cannot get a pointer to that.
Use:
fixed(char* start = &mySentence)
instead.
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.