指標—C# 中的指標 unsafe 欄位

來源:互聯網
上載者:User

        指標可以說是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
         
         

   其實這裡面主要理解 指標的用途。 指標說白了就是地址。指標的指標就是 指向地址的地址。 引用就是別名。 懂得這一點這個問題就非常的好解決了。

如果各位還有其他的好的理解或答案,可以一起分享。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.