Cannot take the address of the given expression C# pointer

前端 未结 3 1836
一整个雨季
一整个雨季 2021-01-06 01:45

Consider the following code in an unsafe context:

string mySentence = \"Pointers in C#\";

fixed (char* start = mySentence) // this is the line we\'re talkin         


        
相关标签:
3条回答
  • 2021-01-06 02:04

    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.

    0 讨论(0)
  • 2021-01-06 02:11

    mySentence[0] returns a readonly single character, you cannot get a pointer to that.

    Use:

    fixed(char* start = &mySentence)
    

    instead.

    0 讨论(0)
  • 2021-01-06 02:17

    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.

    0 讨论(0)
提交回复
热议问题