Cannot take the address of the given expression C# pointer

前端 未结 3 1886
一整个雨季
一整个雨季 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.

提交回复
热议问题