I have a block of code below with one line commented out. What happens in the method CreateArrayis the same as in the numbered line. My question is why it works when the line is b->ArrayItems = duncommented, but return garbage when commenting? I don’t think that I need to “fix” anything because all the information is uncontrollable. Is this assumption wrong?
CreateArray
b->ArrayItems = d
class Program { unsafe static void Main(string[] args) { someInstance* b = stackalloc someInstance[1]; someInstance* d = stackalloc someInstance[8]; b->CreateArray(); // b->ArrayItems = d; *(b->ArrayItems)++ = new someInstance() { IntConstant = 5 }; *(b->ArrayItems)++ = new someInstance() { IntConstant = 6 }; Console.WriteLine((b)->ArrayItems->IntConstant); Console.WriteLine(((b)->ArrayItems - 1)->IntConstant); Console.WriteLine(((b)->ArrayItems - 2)->IntConstant); Console.Read(); } } public unsafe struct someInstance { public someInstance* ArrayItems; public int IntConstant; public void CreateArray() { someInstance* d = stackalloc someInstance[8]; ArrayItems = d; } }
My question is why it works when the line is uncommented, but return garbage when commenting.
- , , CreateArray. , . .
:
, , , , .
CreateArray , , , . stackalloc'd, , . , , , .
, . . , .
, , , " , ?" . , . ; .
-, ; , , , , . , , , , , .
Stackalloc , , (, ). , stackalloc , , .
, :
foo() { stuff = stackalloc byte[1] Do something with stuff }
"" foo, foo, , , :
foo() { byte* allocate() { return stackalloc[1] } stuff = allocate() do something with stuff }
allocate , allocate, , "" .
, . MSDN:
, . . stackalloc.
(.. ), stackalloc.
stackalloc
The deferred stack memory will be discarded after the method completes, hence your problem (see Eric Lipperts), who wrote this in front of me.
Source: https://habr.com/ru/post/1756653/More articles:Can I put files on the iPad simulator? - xcodeотключить добавление теговв fckeditor - fckeditorWhy doesn't PrintPreview match print? - c #What are the default maximum heap sizes for different Sun JVMs? - javaFCKeditor: displays formative characters along with text - formatпередача параметра поиска через jquery - jquerySQL Special Data Load Data - mysqlWerror ignores certain files - c ++Red-black tree - how to turn if the root is grandfather? - javaWordpress: пользовательские типы сообщений: использование настраиваемых полей или таксономии? - searchAll Articles