Fundamental C - Simple Arrays
Written by Harry Fairhead   
Monday, 09 September 2019
Article Index
Fundamental C - Simple Arrays

This extract, from my new book on programming C in an IoT context, explains the basics of the array, This is not as simple as in other languages because it is so simple.

Fundamental C: Getting Closer To The Machine

Now available as a paperback and ebook from Amazon.

  1. About C
      Extract Dependent v Independent
                  & Undefined Behavio
  2. Getting Started With C Using NetBeans
  3. Control Structures and Data
  4. Variables
      Extract Variables 
  5. Arithmetic  and Representation
      Extract Arithmetic and Representation 
  6. Operators and Expression
      Extract Side Effects, Sequence Points And Lazy Evaluation
      First Draft of Chapter: Low Down Data
  7. Functions Scope and Lifetime
  8. Arrays
      Extract  Simple Arrays 
      Extract  Ennumerations ***NEW
  9. Strings
      Extract  Simple Strings 
  10. Pointers
      Extract  Pointers, Cast & Type Punning
  11. Structs
      Extract Basic Structs 
  12. Bit Manipulation
      Extract Shifts And Rotates 
  13. Files
     Extract Files 
  14. Compiling C – Preprocessor, Compiler, Linker
     Extract Compilation & Preprocessor

Also see the companion volume: Applying C







In this chapter we take a look at how arrays are used and how pointers play a role. This is a first look at pointers as it is important that you know they exist and what they are, but there is a full chapter later on which explains the more advanced aspects of pointers. In the next chapter we look at the practicalities of using strings.

The Array

The array solves many problems that would be next to impossible without it. Suppose you need to keep track of the scores of three users. You might well try:


This works, but now generalize it to 100 users or a 1000. Not easy, but with an array it’s very easy. An array is a data structure that consists of lots of repeats of a basic element. Any element can be accessed using a numeric index.

So, for example, the previous user scores using an array would be written:


Notice that the array is called user and it has three elements.

In C you have to declare an array and fix its size before you can use it using an instruction like:

type name[number of elements];

So for example to declare an array of three ints you would use:

int user[3];

The only potentially confusing part is that the array index starts at zero. This means that the declaration creates user[0], user[1] and user[2]. Notice that the declaration gives the number of elements not the value of the final index.

It is important to realize that an array cannot increase or decrease in size once it has been declared.

There are also some confusing rules about how you can specify the size of an array. For arrays defined at file level, i.e. not within a function, the size must be specified as a constant expression. A constant expression is one that can be evaluated at compile time as all of the values are known, e.g. 2*3.

For an array defined within a function, you can use an expression that can only be evaluated at runtime, but only in C99 or later – this is known as a variable length array or VLA. In C89 the GCC compiler will allow runtime expressions and only warn you that you shouldn’t do this if you add -pedantic to the compiler options. What this means is that you can include arrays in functions and set the size when the function is used.

For example:

int sum(int n){
    int myArray[n];
. . .

is fine in C99 and later and works in GCC’s implementation of C89 even if it isn’t part of the standard. Notice that as n isn’t defined at compile time you cannot say what the size of the array is before the program is run. When the function is completed the array is destroyed as is the case for any local variables. If the function is called again then the array is recreated possibly with a different size. In most cases VLAs are best avoided if at all possible.

It doesn’t matter how you specify the size of an array, once declared it cannot change its size without being destroyed and recreated.

You can also initialize an array using curly brackets:

int myArray[6]={0,1,2,3,4,5};

This sets myArray[0] to zero, myArray[1] to one and so on. If you don’t provide enough initializer values then the remaining elements are set to zero. This can be used to set an entire array to zero.

For example:

int myArray[1000]={0};

notice that this only works for zero.

C99 also allows you to specify starting positions for the initialization.

For example:

int myArray[1000]={0,1,2, [10]=10,11,12,13,[500]=500,501};

This sets the first three elements to 0,1 and 2, then zeros elements up to 9 and stores 10 in element 10, 11 in 11 and so on, then zeros 14 up to element 500 where it stores 500, and 501 in element 501. You can see the idea, the initialization restarts at the indicated position in square brackets and any elements not initialized are set to zero.

If you don’t specify the size of the array then it is made large enough to hold all of the initial values:

int myArray[]={0,1,2,3,4,5}; 

Also notice that while ints have been used in the examples, all of this works no matter what the types of the elements are.

For example:

float myArray[]={1.0f,2.0f,3.0f};

creates a three element array of floats.

Arrays and For Loops

So now you know how to create an array and how to initialize one. However, how would you initialize an array with 1000 elements?

The answer, as it is to many uses of the array, is to use a for loop. Arrays and for loops were made for each other. For example, to set a 1000-element array to 1 you would use:

int myArray[1000];
for(int i=0;i<1000;i++){

The array index isn’t restricted to be a simple variable, it can be an expression. You can also assign an expression to an array element. It is this freedom to use expressions that makes C a powerful language. In general anywhere you can use a variable or a literal you can use an expression.

For example, to set the array elements equal to 0, 2, 4, and so on you would use:

int myArray[1000];
for(int i=0;i<1000;i++){

One of the things you have to learn to use C effectively is how to construct index expressions that give you the array elements you want to use. For example, assuming i runs from 0 to the last element:


gives you all the even elements and:


gives you all the odd elements.

For example, to set all the even elements to 1 and the odd elements to -1 you would use:

int myArray[1000];
for(int i=0;i<500;i++){

Once you have seen this sort of approach then you can usually work out an expression that gives you what you need.

Last Updated ( Monday, 09 September 2019 )