基本的C#语法问题

cod*_*ryn 2 c# syntax

class f2011fq1d
{
    unsafe public static void Main()
    {
       int a = 2;
       int b = 4;
       int* p;
       int* q;
       int[] ia = { 11, 12, 13 };
       p = &a; q = &b;
       Console.WriteLine(*p + a);
       Console.WriteLine(*q / *p);
       Console.WriteLine(*&a + *&b * 2);

       *p = a + *q;
       Console.WriteLine(a + *q);
       fixed (int* r = ia)
       {
           Console.WriteLine(*r + 3);
       }
    } 
}
Run Code Online (Sandbox Code Playgroud)

在这段代码中,我对一些语法感到困惑.例如,做什么int* p,p = &a做什么?最后一部分fixed (int* r = ia),那是做什么的?

在源代码中,它还会打印一些值,有人可以解释正在打印的内容吗?

eva*_*nal 7

您正在使用指针和"运算符地址"这些通常与C/C++相关的功能,但在unsafe代码块中的C#代码中可用.我建议对这个概念进行一些一般性的研究,因为单独理解语法不足以有效地使用它们.我会解释几行;

 int * p; //a pointer (the address of) 4 bytes of memory for an int
 int a = 5; // normal allocation/initialization of int
 p = &a; //sets p  to the address of a. Since p is a pointer, it holds an address
 // ampersand is the 'address of operator', it returns and address. so this assignment works


 p = a // will not compile. int* != int

 p == 5 // will not compile, int* != int

 *p == 5 // true. *pointer dereferences the pointer returning the value
 // found at the address p points to which is 5 so this is true.

 int * q = &a; // another pointer to the memory containing a

 p == q // true, both pointers contain the same value, some address which is usually displayed in hex like 0xFF110AB2
Run Code Online (Sandbox Code Playgroud)

指针的更常见用法是类似的;

int *p;
// do something to get a length for an integer array at runtime
p = new int[size]; 
// now I've allocated an array based on information found at run time!
Run Code Online (Sandbox Code Playgroud)

上述操作在C/C++中非常常见,完全是必要的.在C#中,没有必要这样做.它已经在幕后为你完成,它永远不会出错(比如没有释放我刚刚分配的内存).