Arrays – C

Arrays are most common data structures which can store a collection of elements which are:

  1. same type
  2. sequential

Most simple way of thinking about arrays is variables of same type which have similar purpose. For example income for each month in a year – array would have 12 elements of which each element corresponds to month.

Arrays have fixed size and each array has an index and a value corresponding to that index. Memory addresses where values are stored are sequential and indexing starts from 0 and ends with an index of array size – 1.

In C there are 3 types of arrays:

  • Statically allocated array
    • Declared with a fixed size
    • Declared compile-time
    • Possible to initialize at declaration
  • Variable Length Array (VLA)
    • Declared runtime
    • Cannot be initialized at declaration
  • Dynamically allocated array (Won’t be covered in this post)
    • Declared and size specified runtime
    • Possible to resize
    • Complex to manage for beginners

Declaring

Array is a variable like any other, before its usage one has to declare it first. To declare an array the most common way is to specify the type, array name and its size this can be done as follows : type name[size]; e.g. declaring an array of 10 integers int grades[10];. When declaring arrays like this, the programmer must know beforehand how many elements are needed.

If for some reason size can’t be specified in advance, it is possible to let the preprocessor do the counting of how many elements you need. This can only be done when the array is initialized at declaration (see next paragraph for initialization). E.g. with the following statement : char string[] = "CodingMeta"; an array named string and it will have 11 elements (for characters and null terminator).

Using VLA’s enables user to declare arrays depending on the program flow / user input – meaning that at the start of the program it is unknown how big should an array be. This means that the size must be specified e.g. size should be stored in a variable and that variable should be used to declare an array. Example of declaring VLA:

int n;
scanf("%d", &n);
char arr[n];

Initializing

When declaring an array, the program will get a chunk of memory region to fit all the elements inside. This memory is in RAM and might have data from other programs which were running and had their data in that memory region. This is why you can’t assume that your array will be filled with 0 values. To make sure that you have either 0 values or the desired values one must initialize the array.

Initialization can be done by using assignment operator. To initialize array one must use curly braces to give each element a certain value of which each value is separated by a comma.

Declaring and initializing arrays:

  • Fixed size array, different values
    int array[5] = {15, 16, -22, 66, 0};

    • Multi dimensional array, different values
      // More readable version
      int array[3][3] = {
          {1, 2, 3},
          {4, 5, 6},
          {7, 8, 9}
      };
      
      // Also valid
      int array[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
  • Fixed size array, all zeroes
    int array[5] = {0};

    • Multi dimensional array, all zeroes
      int array[5][5] = {0};
  • String, each element separately
    char string[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
  • String, without specifying length
    char string[] = "CodingMeta";

Since VLA’s cannot be initialized one useful trick to set initial data would be to use memset function or to iterate over all of the array elements.

Accessing elements

In order to read or modify the data in array, it is necessary to access it first. This can be done by typing the variable name and then in brackets the index of the element which will be read or modified – format: array_name[index]. For example array[3] = 245; would access the 4th element (indexes start from 0) and assign a new value to it 245.

NB! When accessing array elements, make sure you are within array bounds! 
This means that if you declare an array with 10 elements, the last index you can access is 9. If next elements were to be accessed you’d get garbage data because you are accessing memory that might not belong to your program.
Example:

unsigned char array[10] = {0};
char string[] = "CodingMeta";

for (int i = 0; i < 22; i++) {
    array[i] = 49 + i;
}
printf("string: '%s'\n", string);

Output:
string: 'ABCDEFMeta'

Dimensions

Arrays can have multiple dimensions most commonly 1D (aka vector) and 2D arrays are used. It might help to visualize 2D array as in a plain, with rows as one of the sizes and columns as the other. To create arrays with multiple dimensions it is necessary to specify the type, name andsizes of the dimensions within brackets type name[sized1][sizedn]. Here are two examples about 1D and 2D arrays:

1D array

char str[6] = "Hello";

This statement will create an array named str with a size of 6 elements, which is initialized to a value “Hello”. This array can be represented in memory as follows:

character array in memory

Notice how the memory addresses are incremented by one – this is because the size of char is 1 (see data types). Each of the elements can be accessed by an index which can be seen on the first row in the picture.

2D array

int array[3][3] = {
    {-11, 1, 11},
    {-22, 2, 22},
    {-33, 3, 33}
};

This statement will create an array named array which contains integers, and it has 3*3 elements in size. This can be represented in memory as follows:

2d integer array in memory

In the picture the values are shown as big bold numbers and the memory addresses as italic 64-bit hexadecimal number. Notice how in the memory all of the memory addresses are sequential with 4 byte increments (exactly the size of int). This means that all of the elements are actually sequential in memory and can be accessed by using row and column index.

 

Resources

  1. Arrays [ Link ]

3 thoughts on “Arrays – C

Comments are closed.