日期:2014-05-18  浏览次数:20835 次

VS2008中结构体是在stack上还是在heap上啊?
书上说C#的struct是值类型,运行在stack上,但是小弟写了一个unsafe的代码,分析struct的分配情况,居然发现struct的地址分配从低到高?难道struct在heap上分配资源
以下是代码:
C# code

using System;

namespace Point
{
    class CurrencyClass
    {
        public long Dollars;
        public byte Cents;
        public override string ToString()
        {
            return "$" + Dollars + "." + Cents;
        }
    }

    struct CurrencyStruct
    {
        public long Dollars;
        public byte Cents;
        public override string ToString()
        {
            return "$" + Dollars + "." + Cents;
        }
    }

    class EnterPoint
    {
        static unsafe void Main()
        {
            Console.WriteLine("size of Currency struct is"+sizeof(CurrencyStruct));
            CurrencyStruct amount1, amount2;
            CurrencyStruct* pAmount = &amount1;
            long* pDollars = &(pAmount->Dollars);
            byte* pCents = &(pAmount->Cents);
            Console.WriteLine("address of amount1 is 0x{0:X}",(uint)&amount1);
            Console.WriteLine("address of amount2 is 0x{0:X}",(uint)&amount2);
            Console.WriteLine("address of pAmount is 0x{0:X}",(uint)&pAmount);
            Console.WriteLine("address of pDollars is 0x{0:X}",(uint)&pDollars);
            Console.WriteLine("address of pCents is 0x{0:X}", (uint)&pCents);
            pAmount->Dollars = 20;
            *pCents = 50;
            Console.WriteLine("amount1 contains" + amount1);
            --pAmount;
            Console.WriteLine("amount2 has address 0x{0:X} and contains {1}",(uint)pAmount,*pAmount);
            CurrencyStruct* pTempCurrency = (CurrencyStruct*)pCents;
            pCents=(byte*)(--pTempCurrency);
            Console.WriteLine("Address of pCents is now 0x{0:X}",(uint)&pCents);
            Console.WriteLine("\nNow with classes");
            CurrencyClass amount3 = new CurrencyClass();
            fixed (long* pDollars2 = &(amount3.Dollars))
            fixed (byte* pCents2 = &(amount3.Cents))
            {
                Console.WriteLine("amount3.Dollars has address 0x{0:X}",(uint)pDollars2);
                Console.WriteLine("amount3.Cents has address 0x{0:X}", (uint)pCents2);
                *pDollars2 = -100;
                Console.WriteLine("amount3 contains" + amount3);
            }
        }
    }
}




------解决方案--------------------
你用的是指向CurrencyStruct的指针变量
------解决方案--------------------
这个要看你struct里都是什么类型的变量
------解决方案--------------------
如果含有不安全类型比如指针那应该是放在了非托管堆里...