C#的指针
刚才在看MSDN,在《C#参考》的运算符关键字中有这样一段代码:
1// cs_keyword_stackalloc.cs
2// compile with: /unsafe
3using System;
4class Test
5{
6 static unsafe void Main()
7 {
8 int* fib = stackalloc int[100];
9 int* p = fib;
10 *p++ = *p++ = 1;
11 for (int i = 2; i < 100; ++i, ++p)
12 {
13 *p = p[-1] + p[-2];
14 }
15 for (int i = 0; i < 10; ++i)
16 {
17 Console.WriteLine(fib[i]);
18 }
19 }
20}
2// compile with: /unsafe
3using System;
4class Test
5{
6 static unsafe void Main()
7 {
8 int* fib = stackalloc int[100];
9 int* p = fib;
10 *p++ = *p++ = 1;
11 for (int i = 2; i < 100; ++i, ++p)
12 {
13 *p = p[-1] + p[-2];
14 }
15 for (int i = 0; i < 10; ++i)
16 {
17 Console.WriteLine(fib[i]);
18 }
19 }
20}
一开始没有看懂p[-1] + p[-2]这个表达式,觉得很奇怪。常见的表达式应该是p[i-1] + p[i-2],而且我们知道[]中的索引应该是一个大于等于0的数,这里出现负数,不合理啊!
琢磨良久,突然想起很久以前看过一本C/C++的书,记得有一页的脚注中提到C数组的本质:
有 int a[] = {1,2,3,4,5},i>=0,i<=4
则 a[i] = *(a+i) = *(i+a) = [i]a
原来如此!