Stride of An Array - Reasons For Non-unit Stride

Reasons For Non-unit Stride

There are at least two reasons arrays may have a stride larger than their elements' width in bytes. First, many languages (including C and C++) allow structures to be padded to better take advantage of the word length of the machine. For example:

struct ThreeBytesWide { char a; }; struct ThreeBytesWide myArray;

In the above code snippet, myArray might well turn out to have a stride of four bytes, rather than three, if the C code were compiled for a 32-bit architecture, and the compiler had optimized (as is usually the case) for minimum processing time rather than minimum memory usage.

Second, some languages allow arrays of structures to be treated as overlapping parallel arrays with non-unit stride:

#include struct MyRecord { int value; char *text; }; /* Print the contents of an array of ints with the given stride */ void print_some_ints(const int *arr, int length, size_t stride) { int i; printf("Address\t\tValue\n"); for (i=0; i < length; ++i) { printf("%p\t%d\n", arr, arr); arr = (int *)((unsigned char *)arr + stride); } } int main(void) { int ints = {0}; struct MyRecord records = {0}; print_some_ints(&ints, 100, sizeof ints); print_some_ints(&records.value, 100, sizeof records); return 0; }

This idiom is a form of type punning.

Read more about this topic:  Stride Of An Array

Famous quotes containing the words reasons for, reasons and/or stride:

    The lore of our fathers is a fabric of sentences.... It is a pale gray lore, black with fact and white with convention. But I have found no substantial reasons for concluding that there are any quite black threads in it, or any white ones.
    Willard Van Orman Quine (b. 1908)

    Given the existence ... of a personal God ... who ... loves us dearly ... it is established beyond all doubt ... that man ... wastes and pines ... for reasons unknown.
    Samuel Beckett (1906–1989)

    I, in my intricate image, stride on two levels....
    Dylan Thomas (1914–1953)