Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot take the address of the given expression C# pointer

Tags:

c#

pointers

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.

like image 634
Snake Avatar asked Feb 22 '11 14:02

Snake


2 Answers

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:

  • The address operator & applied to a variable reference.
  • An array
  • A string
  • A fixed-size buffer.

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.

like image 50
Eric Lippert Avatar answered Nov 04 '22 13:11

Eric Lippert


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.

like image 36
as-cii Avatar answered Nov 04 '22 12:11

as-cii