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.
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]
c sharp ?? A |