Originally published by Robert Beisert at fortcollinsprogram.robert-beisert.com

Linux + C – Arrays

Let’s be honest, folks. We don’t expect to work with a few clearly defined variables forever. Sometimes we need to handle a lot of things at once, or at least a group of related things.

The simplest method for lumping a group of things together is the basic data array.

Arrays

An array is a set of data elements which are a) referenced by the same variable name and b) indexed.

Arrays are initialized (created) by defining the number of elements we will allow our variable to store. It is very important that we set a number which is large enough to handle our problem, but small enough to not take up a ridiculous amount of space.

From this point on, the variable name is basically a pointer to the first element in the array. To reach any other element, we simply input the index of that element, and the computer handles the rest.

For example, we can create an array of five characters using the following code:

char SetofFive[5] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’}

This code says the following things:

  • We want an array of 5 characters
  • We will declare the values of these five characters when we create the array
  • The values of these characters are, in order, ‘a’, ‘b’, ‘c’, ‘d’, and ‘e’

Suppose we now want to print out the array in reverse order. We can do that by referencing the indices, as such:

printf(“%c %c %c %c %cn”, SetofFive[4], SetofFive[3], SetofFive[2], SetofFive[1], SetofFive[0])

And that’s it.

Note: We initialize an array by declaring HOW MANY elements will be in the array. However, we start indexing at 0. That’s why the SetofFive indexes range from 0 to 4.

array_eg.c


#include <stdio.h>
//We need this to generate random numbers
#include <stdlib.h>
//We need this to make random numbers actually random
#include <time.h>

int main(int argc, char *argv[])
{
//Create an array of 25 elements
int RandomNumbers[25];
//Create an iterator for later
int i=0;
//We can also let the computer determine how big the array should be...
//IF we put a specifically sized value into it.
char Message[] = "This is a message from me to you";

//Seed the random number generator (set it up to be random)
srand(time(NULL));

//Store a random number between 0 and 364 into each index
for(i=0; i<25;i++)
{
//rand() creates a random number in the entire size of integers
//We want to limit it to the values below 365, so we use the modulo operation
RandomNumbers[i] = rand() % 365;
}

//What the hey. Let's print it backwards.
for(i=0; i<25; i++)
{
printf("Random Number %d = %d\n", 25-i, RandomNumbers[25-i]);
}

printf("%s/n", Message);
}

No special tags on this one. Just compile with gcc as always.