开发者

Cannot take the address of the given expression C# pointer

Consider the following code in an unsafe context:

string mySentence = "Pointers in C#";

fixed (char* start = mySentence) // th开发者_StackOverflow社区is 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:

  • 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜