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]!='\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: ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.