ein mensch ein mensch - 7 months ago 49
C Question

Split C Array on element

Say, I have an array

and a predicate
, I want to split the array into different sub-arrays
on every element matching

So something like:

typedef bool (*P) (T element);
T**subs(T*array,P p){....}

How can the code for
look like?

Note, that the code is just pseudo code, you can use variables like
and so on in your example, because I just want to get the idea on how to implement


We call that a callback function, not predicate.

typedef bool (*P) (T element);

T * * subs(T * array, P callback) {
    T * * retval = malloc(sizeof(T*) * max_groups); // either count before, or realloc as needed
    size_t group = 0;
    retval[group] = array;

    for (size_t i = 0; i < array_length; ++i) {
        if (callback(array[i])) {
            retval[++group]=array + i;

    return retval;

This reuses the memory of the argument array and doesn't return any information about the lengths of the groups, but since you only wanted a general idea on how to solve this, I think this should be enough starting point for you to get exactly what you want.