Arrays in C vs Java

An array is a data structure consisting of a collection of elements or values, each identified by unique index. There are multiple ways to create an array in C. The methods shown in this section are easier to use, but they result in arrays that are not permanent.

This code creates a new array of 20 ints called myArray:

int myArray[20]; // array of 20 ints 

Usually the elements of this array are not initialized. Do not assume that they all start out holding 0.

Alternatively, we can also leave out the size but include the elements explicitly:

int fib[] = {0, 1, 1, 3, 5, 8, 13, 21, 34, 55}; // 10 ints 

This results in an array of size 10, holding the first numbers of the Fibonacci sequence.

The problem with these arrays is that they are treated like local variables. They will cease to exist after the function they’re in has ended. Thus, these techniques cannot be used if the array needs to be permanent. Trying to return these arrays, or use them after the function has stopped, can result in strange errors in which your program terminates or unrelated data gets changed, seemingly at random. We will discuss this further when we talk about memory and pointers. We will also discuss a way to make a permanent array.

What’s more, you must be very careful when indexing an array in C. In Java, you immediately get an ArrayIndexOutOfBoundsException when you try to access an illegal element in an array. For example, the array fib that we created has only 10 elements: fib[0] through fib[9]. If you tried to access fib[10] or fib[-1], your Java program would immediately stop and let you know there was a problem. C has no such boundary checking: if you tried to access fib[10], C would just look at the memory where fib[10] would be if it existed, and return that data as if it were an int. Even worse, if you mistakenly wrote to fib[10], it would change the data where fib[10] would be—altering some unrelated data! Be careful!

Another issue is that C arrays do not have a length property, unlike in Java. There is no way to calculate the length of the array from the array itself. If the length of an array can vary, its length must be stored in a int. It is very common when one writes a function that takes an array as an argument, that it has a second argument indicating that array’s length:

// this function has an array argument & a length argument
int doThingWithArray(int array[], int arrayLength) {
}

Some people might try to do a sizeof(myArray). However, this will only work from inside the same function as the array was declared, and only if done using one of these”temporary” methods. It usually only tells you the size of the array’s address in memory, which is not helpful.


Licenses and Attributions


Speak Your Mind

-->