指標可以說是C和C++ 中特有的,出於安全性的考慮,微軟出的C# 中取消了指標的運用,但是,在C#中仍有關鍵字 unsafe 關鍵字裡 可以編寫C++ 代碼。因為 unsafe 是要以時間和空間消耗為代價的。 所以不經常使用,其主要用途是在處理大量的數組的時候,有大量的地址在變化的時候用 unsafe 關鍵字就有可能贏得更大的效力。 前不久, 在和朋友討論一個問題,問題的描述如下代碼所示:
Code
using System;
using System.Collections.Generic;
using System..Linq;
using System..Text;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
Int32 i = 0;
Console.WriteLine("Before unsafe code, i = {0}", i);
long l = 0;
unsafe // Seg 1
{
l = (long)&i;
l++;
char* ptr = (char*)l;
*ptr = 'a';
}
Console.WriteLine("After unsafe code seg 1, i = {0}", i);
unsafe // 2
{
char* ptr = (char*)l;
Console.WriteLine("Inside unsafe code seg 2, *ptr = {0}", *ptr);
}
Console.WriteLine("QUESTION: There is no code to modify variable i directly, why the value of i is changed to 24832?");
}
}
}
OUTPUT:
Before unsafe code, i = 0
After unsafe code seg 1, i = 24832
Inside unsafe code seg 2, *ptr = a
QUESTION: There is no code to modify variable i directly, why the value of i is changed to 24832?
Press any key to continue . . .
我們可以看到輸出的結果是 24832。 這是怎麼回事呢? 以下是我個人的分析:
Int32 i = 0; Console.WriteLine("Before unsafe code, i = {0}", i); long l = 0; unsafe // Seg 1 { l = (long)&i; l++; char* ptr = (char*)l; *ptr = 'a'; } |
高2 |
高1 |
低2 |
低1 |
|
00 |
00 |
00 |
00 |
<<== i 的值(0)在 16進位中的表示,此時 l 指向了低1位 0 |
00 |
00 |
00 |
00 |
<<== 執行l++, l 指向了低二位 |
00 |
00 |
00 |
00 |
<<= 執行 char* ptr = (char*)l; ptr 也指向了低2位 |
00 |
00 |
a |
00 |
<<= 執行 *ptr = 'a'; 低2位賦值 為 a |
00 |
00 |
61 |
00 |
<<= ‘a’ 的ASCLL 碼的十六進位為 61 |
24832 |
<<= 把 I 轉換為10進位輸出 24832 |
|
|
|
|
|
|
|
|
|
|
其實這裡面主要理解 指標的用途。 指標說白了就是地址。指標的指標就是 指向地址的地址。 引用就是別名。 懂得這一點這個問題就非常的好解決了。
如果各位還有其他的好的理解或答案,可以一起分享。