Getting pointer for first entry in an array

江枫思渺然 提交于 2019-12-22 02:03:02

问题


I want to get pointer of first entry in the array. This is how I tried

int[] Results = { 1, 2, 3, 4, 5 };

unsafe
{
    int* FirstResult = Results[0];
}

Get following compilation error. Any ideas how to fix it?

You can only take the address of an unfixed expression inside of a fixed statement initializer


回答1:


The error codes are magic to get the answer - search for error code (CS0212 in your case) and you get explanation with proposed fix in a lot of case.

Search: http://www.bing.com/search?q=CS0212+msdn

Result: http://msdn.microsoft.com/en-us/library/29ak9b70%28v=vs.90%29.aspx

Code from the page:

   unsafe public void mf()
   {
      // Null-terminated ASCII characters in an sbyte array 
      sbyte[] sbArr1 = new sbyte[] { 0x41, 0x42, 0x43, 0x00 };
      sbyte* pAsciiUpper = &sbArr1[0];   // CS0212
      // To resolve this error, delete the previous line and 
      // uncomment the following code:
      // fixed (sbyte* pAsciiUpper = sbArr1)
      // {
      //    String szAsciiUpper = new String(pAsciiUpper);
      // }
   }



回答2:


The error message is pretty clear. You can refer to MSDN.

unsafe static void MyInsaneCode()
{
    int[] Results = { 1, 2, 3, 4, 5 };
    fixed (int* first = &Results[0]) { /* something */ }
}



回答3:


Try this:

unsafe
{
    fixed (int* FirstResult = &Results[0])
    {

    }
}


来源:https://stackoverflow.com/questions/9946550/getting-pointer-for-first-entry-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!