Reputation: 6222
We have an array with pointers to generic arrays, and an array of generic functions, we want to apply to each element in array i
the function i
from func_ptarrs
.
typedef struct genarr{
void * arr;
int elemsize;
int numelem;
}GENARR;
typedef void(*funcptr)(void*);
typedef unsigned char byte;
void updateall(GENARR *arrs, funcptr *func_ptarrs, int n){
int j,i;
for (i = 0; i < n; i++){
for (j = 0; j < arrs[i].numelem; j++){
func_ptarrs[i]((arrs[i].((byte*)(arr + j*arrs[i].elemsize)))); //error: expected member name
//func_ptarrs[i]((arrs[i].arr)); //no error
}
}
}
In the second try it's pointer to the beginning of the array so it's accepted, but I need to be able to send each element of the array to the generic function.
I don't understand how to send the right amount of bytes and move correctly in array all while sending pointers of the elements to the generic functions.
Maybe I should use memcpy
?
Upvotes: 0
Views: 647
Reputation: 53016
You need this instead,
func_ptarrs[i](((byte*) arrs[i].arr + j * arrs[i].elemsize))
and I think it's pretty obvious why it would work.
You could write accessor macros too, like
#define ARRAY_VALUE(type, x, i (*(type *) ((x).arr + (i) * (x).elemsize))
which you can then use like
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_VALUE(type, x, i) (*(type *) ((x).arr + (i) * (x).elemsize))
typedef struct genarr
{
void * arr;
int elemsize;
int numelem;
} GENARR;
int main (void)
{
GENARR array;
int data[10];
array.arr = data;
array.elemsize = sizeof(*data);
array.numelem = sizeof(data) / array.elemsize;
for (int i = 0 ; i < array.numelem ; ++i)
ARRAY_VALUE(int, array, i) = i;
for (int i = 0 ; i < array.numelem ; ++i)
printf("%d\n", ARRAY_VALUE(int, array, i));
return 0;
}
Upvotes: 1