Use Insecure code to create and use Arrays on stacks

Source: Internet
Author: User

An array is a class object, and the storage space is on the stack. It is a reference type. So how to create and access array elements on the stack for higher efficiency? The following is an example of CLR via C #.CodeUse stackalloc and create Schema-type instances to implement the use of arrays on the stack.

 

 Public   Static   Class Program { Public   Static   Void Main () {stackallocdemo (); inlinearraydemo ();} Private   Static   Void Stackallocdemo (){ Unsafe { Const Int32 width = 20; char * Pc = Stackalloc Char [width]; // Allocates array on Stack String S = "Jeffrey Richter" ; // 15 characters                      For (Int32 Index = 0; index <width; index ++) {PC [width-index-1] = (index <S. Length )? S [Index]: '.' ;} // The line below displays "... rethcir yerffej" Console. writeline ( New String (PC, 0, width ));}} Private   Static   Void Inlinearraydemo (){Unsafe {Chararray CA; // Allocates array on Stack Int32 widthinbytes = Sizeof (Chararray); int32 width = widthinbytes/2; string S = "Jeffrey Richter" ; // 15 characters            For (Int32 Index = 0; index <width; index ++) {ca. characters [width-index-1] = (index <S. Length )? S [Index]: '.' ;} // The line below displays "... rethcir yerffej" Console. writeline ( New String (ca. characters, 0, width ));}}} Internal   Unsafe   Struct Chararray { // This array is embedded inline inside the structure     Public   Fixed Char characters [20];}
 
 
 
In the inlinearraydemo function above, the structure type instance must allocate space on the stack. Therefore, if a char array is embedded in the chararray struct, the char array will also be allocated to the stack.
 
Both methods use Insecure code, so be careful when using them.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.