Sorted List Presentation, Part III

Once you accept that a program’s data set is flexible, you must abandon all constants and use variables. It’s a good move: The variables ensure that no matter what changes with the data, the code can handle it.

For the sample program in this series, I’ve assumed several constants:

  1. The number of elements in the array.
  2. The length of the widest string in the array.
  3. The number of columns in the output.
  4. The number of rows in the output.

Believe it or not, the difficult part of the code was completed in last week’s Lesson: Set the output sorted by columns instead of rows. That’s over. Now, to make the code adaptable to a changing number of array elements, you must craft the four items above as variables instead of constants.

Of course, not everything is a variable. Moving forward, you must make one assumption: The terminal window is fixed at 80 columns for output. I recommend setting this value as a defined constant. That way it could be reset later if you move the code to an environment where the terminal width changes or can otherwise be obtained at runtime.

The first challenge is to discover the number of elements in the array.

C lacks the capability to define dynamic arrays. You can declare an array using a set value, such as:

char *fruit[35];

Or you can declare the array and assign values, in which case the compiler does the math:

    char *fruit[] = {
        "apple", "orange", "blueberry", "date", "melon",
        "grape", "peach", "mango", "watermelon", "pear",
        "olive", "plum", "nectarine", "kiwi", "loquat",
        "honeydew", "lime", "grapefruit", "cherry",
        "avocado", "tomato", "banana", "cantaloupe",
        "huckleberry", "kumquat", "tangerine", "fig",
        "raspberry", "papaya", "lychee", "guava",
        "persimmon", "coconut", "cranberry", "chestnut"
    };

The second method is better when you plan on adding or removing array elements as you code. And you could count the elements by hand, but the point of this Lesson is to let the code handle that operation. The solution is to the use sizeof operator. For example:

#include <stdio.h>

int main()
{
    int array[] = {
        2, 3, 5, 7, 11
    };

    printf("The size of 'array' is %lu\n",
            sizeof(array));

    return(0);
}

The sizeof operator returns the amount of storage (bytes) occupied by the array[] variable. Here’s the output:

The size of 'array' is 20

You know that array doesn’t contain 20 elements; it’s not a string. It’s an int array, so if you divide its storage size by the size of an int, you get the size of the array:

sizeof(array)/sizeof(int)

That change to the code yields the value 5, the number of elements in the array.

When you use sizeof on a char array (a string), it returns the length of the string plus 1 for the null character, '\0', which is the final element of the array.

The fruit[] array contains pointers, specifically char pointers. To return its size, the following calculation is used:

sizeof(fruit)/sizeof(char *);

The sizeof(fruit) operator returns the storage space occupied by the entire fruit array. That value is divided by the the size of a char pointer, sizeof(char *). The result is the number of elements in the array:

#include <stdio.h>

int main()
{
    char *fruit[] = {
        "apple", "orange", "blueberry", "date", "melon",
        "grape", "peach", "mango", "watermelon", "pear",
        "olive", "plum", "nectarine", "kiwi", "loquat",
        "honeydew", "lime", "grapefruit", "cherry",
        "avocado", "tomato", "banana", "cantaloupe",
        "huckleberry", "kumquat", "tangerine", "fig",
        "raspberry", "papaya", "lychee", "guava",
        "persimmon", "coconut", "cranberry", "chestnut"
    };
    int items;

/* count the items in the array */
    items = sizeof(fruit)/sizeof(char *);
    printf("The 'fruit' array has %d elements\n",
            items);

    return(0);
}

Here’s the output:

The 'fruit' array has 35 elements

The first challenge is complete: The code can obtain the number of elements in the array as a variable. In next week’s Lesson, I explore the remaining options to create variables from values once assumed to constants.

Leave a Reply