How to use callback with arrays of structs (apply callback to each struct) in C

1 Answer

0 votes
#include <stdio.h>

// Using callbacks with arrays of structs

typedef struct {
    int value;
} Item;

// Callback that modifies a struct 
void increment(Item *item) {
    item->value += 10;
}

// Apply callback to each struct 
void apply(Item *arr, int size, void (*callback)(Item *)) {
    for (int i = 0; i < size; i++) {
        callback(&arr[i]);
    }
}

int main() {
    Item arr[] = {{1}, {2}, {3}};
    int size = sizeof(arr) / sizeof(arr[0]);

    apply(arr, size, increment);

    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i].value);
    }
}


 
/*
run:
 
11 12 13 
 
*/

 



answered Mar 19 by avibootz
...