Unlike the Java runtime system, the C++ runtime system has no intrinsic way of knowing the size of an array, even if it has been declared with a compile-time constant size. The primary differences related to using arrays in C++ as opposed to using them in Java are due to this very significant difference.
As a concrete example, you know you can write a Java method to return the sum of the numbers in an array as follows:
double sum(double[ ] buf) // Java version { double s = 0.0; for (int i=0 ; i<buf.length ; i++) s += buf[i]; return s; }
Moreover, any attempt to access an array location outside the bounds of the array will result in an immediate runtime exception being thrown.
Since the C++ runtime system cannot determine the length of an array:
Therefore you must make sure that any code processing an array has a way of ensuring that it only uses valid indices. There are many conventions for that. One very common approach when passing arrays to methods is to pass not only the array itself, but also its length. For example, a typical way to translate the array summing code we saw above from Java to C++ would be as follows:
double sum(double buf[ ], int bufLength) // C++ version { double s = 0.0; for (int i=0 ; i<bufLength ; i++) s += buf[i]; return s; }
Notes:
double sum(double[ ] buf) // Another Java version using the "for each" construct { double s = 0.0 for (double v : buf) // "for each v in buf": supported in Java, but not in C++ s += v; return s; }
Array Initialization
C++ arrays can be initialized using a brace notation in very much the same way as they are in Java:
Java | C++ |
double[] x = new double[] { 1.1, 2.2, 3.3 }; |
double x[] = { 1.1, 2.2, 3.3 }; |