Implementing a generical 'map' function over arrays in C

后端 未结 3 1332
轻奢々
轻奢々 2020-12-30 09:40

I\'m having difficulties implementing a generic \'map\' function over arrays. I started with the following draft:

void MapArray(void * src, void * dest, void         


        
3条回答
  •  余生分开走
    2020-12-30 10:26

    There's a reason nothing much like this is in the C standard library -- it's next to impossible to do it well in C. You can't copy the result, "byte by byte" to dest[i] -- since you've cast dest to a char *, it only points to one char (byte).

    Presumably, elem is intended to be the size of whatever type f returns, and n is the number of elements in src and dest. In that case, your code isn't too far off, but (as you've apparently surmised) the way you're manipulating the pointers (especially the cast to char *) isn't going to cut it.

    Even if you fix that, however, you'll have one other problem: assigning the return type from f without knowing the type is going to be really (really) difficult. In fact, about the only way I can think of is to wrap this code up into a macro instead:

    #define MapArray(s, d, f, n) \
    do {                         \
       unsigned i;               \
       for (i = 0; i

    You'd use this something like this:

    int f(int a) { return a + 100; }
    
    #define elements(array) (sizeof(array)/sizeof(array[0]))
    
    int main() { 
        unsigned i;
        int x[] = { 0, 1, 2, 3};
        int y[elements(x)];
    
        MapArray(x, y, f, elements(x));
    
        for (i=0; i

    Take note: I'm not recommending this. This is a way to do what you're asked for, but as I said to start with, this is next to impossible to do well in C. This code works to some degree, but IMO it does not qualify as doing the job well.

提交回复
热议问题