Skip to content
Physics and Astronomy
Home Our Teaching Resources C programming Common mistakes
Back to top
On this page
Contents

Common mistakes with arrays

Going over the end of the array

There are (at least) two versions of this:

Forgetting that the first index is 0 and the last N-1

Wrong Right
 
 

Using <= in a for() loop, not <

Wrong Right
 
 

Trying to use an array declaration in a function call

Recall that C gives us an easy way to declare a function that expects the address of an array:

So we can declare a function expecting the address of an array as follows:

void printarray(int output[N]);

or:

void printarray(int output[]);

Some students will then sometimes try to call the function with something like:

Wrong Right
  int num[N] = {1, 2, 3, 4};

  printarray(int num[N]);
  int num[N] = {1, 2, 3, 4};

  printarray(num);
This has no chance of success as the incorrect call is trying to say "create a brand new array just for use as an argument to printarray() and give it the same name as an array that already exists". This is meaningless and the compiler will disallow it immediately.

The coreect way to to recall the rule:

Thus passing the name of the array actually passes the address of the array as required.

Passing the value of a non-existent array element to a function

A variation of the above, which is much more dangerous, is to pass the array name and its dimension but without the type (in this case "int"):

Wrong Right: same as above
 int num[N] = {1, 2, 3, 4};

  printarray(num[N]);
 
which forgets the rule:

So instead of passing the address of the array as required the call tries to send the value of fifth element of a four-element array. Depending on your compiler options the compiler may or may not allow this, and if it does your program will crash horribly.

Try stepping through the "good" example first and note how the function correctly receives the address of the array num. Then try the bad example and see how it receives a random, very large number. When it tries to go to that non-existent memory address the program crashes.

Wrong Right
 
 
Log in
                                                                                                                                                                                                                                                                       

Validate   Link-check © Copyright & disclaimer Privacy & cookies Share
Back to top