Mixing two arrays by alternating elements two by two

It is very fiddly to calculate the array indices explicitly, especially if your arrays can be of different and possibly odd lengths. It is easier if you keep three separate indices, one for each array:

int pairwise(int c[], const int a[], size_t alen, const int b[], size_t blen)
    size_t i = 0;       // index into a
    size_t j = 0;       // index into b
    size_t k = 0;       // index into c

    while (i < alen || j < blen) {
        if (i < alen) c[k++] = a[i++];
        if (i < alen) c[k++] = a[i++];
        if (j < blen) c[k++] = b[j++];
        if (j < blen) c[k++] = b[j++];

    return k;

The returned value k will be equal to alen + blen, which is the implicit dimension of the result array c. Because the availability of a next item is checked for each array operation, this code works for arrays of different lengths and when the arrays have an odd number of elements.

You can use the code like this:

#define countof(x) (sizeof(x) / sizeof(*x))

int main()
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int b[] = {-1, -2, -3, -4, -5, -6};

    int c[countof(a) + countof(b)];
    int i, n;

    n = pairwise(c, a, countof(a), b, countof(b));

    for (i = 0; i < n; i++) {
        if (i) printf(", ");
        printf("%d", c[i]);

    return 0;

(The example is in C, not C++, but your code doesn’t use any of C++’s containers such as vector, so I’ve uses plain old ´int` arrays with explicit dimensions, which are the same in C and C++.)

Browse More Popular Posts

Leave a Comment