An array bound defines the valid index range of an array. .NET checks array access automatically, while C++ pointer-based heap access can read beyond the array into unrelated memory. section 1.5.3 section 10.3.4
Length-driven iteration
A C# sum routine allocates an array, fills indexes from zero through the final valid position, and iterates using arr.Length. The array length supplies the loop boundary instead of requiring a separately maintained size. section 1.5.3
Listing 1.2 Creating a dynamic array in C#
public class Program
{
public static void Main()
{
int n = 4, i;
int[] p = new int[n]; #1
Console.WriteLine("Enter elements of array : ");
for (i = 0; i < n; i++) {
p[i] = int.Parse(Console.ReadLine()); #2
}
Console.WriteLine("Sum : " + Sum(p)); #3
}
private static int Sum(int[] arr)
{
int i, sum = 0;
for (i = 0; i < arr.Length; i++) #4
{
sum += arr[i];
}
return sum;
}
}
Inspect the C# implementation to see allocation, indexed assignment, and Length-based traversal working together. section 1.5.3
