29.14 A further example


To finish this chapter, here is another example of how you can access beyond the boundaries of an array [19] in unsafe codes. Study this program carefully “ it should be self-explanatory.

[19] This is impossible in Java or safe C# codes, but could be done easily in C and C++ where array boundaries are not checked for the developer.

 1: using System;  2:  3: class TestClass{  4:  5:   static string name = "c sharp";  6:  7:   unsafe static void PerformOp(char* p) {  8:     int i;  9: 10:     // will print out 'c sharp' (7 characters) 11:     for (i=0; p[i]!=' 
 1: using System; 2: 3: class TestClass{ 4: 5: static string name = "c sharp"; 6: 7: unsafe static void PerformOp(char* p) { 8: int i; 9: 10: // will print out 'c sharp' (7 characters) 11: for (i=0; p[i]!='\0'; i++) 12: Console.Write(p[i]); 13: 14: // will print out 13 more characters which 15: // are beyond the array boundaries. 16: for (int j=i; j<20; j++) 17: Console.Write(p[j]); 18: } 19: 20: unsafe static void Main() { 21: fixed (char* p = name) 22: PerformOp(p); 23: } 24: } 
'; i++) 12: Console.Write(p[i]); 13: 14: // will print out 13 more characters which 15: // are beyond the array boundaries. 16: for (int j=i; j<20; j++) 17: Console.Write(p[j]); 18: } 19: 20: unsafe static void Main() { 21: fixed (char* p = name) 22: PerformOp(p); 23: } 24: }

Output: [20]

[20] Output may differ depending on what is stored beyond your array's allocated space.

 c sharp  ??   A 


From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net