0

I was wondering if it is possible in C to get the type from an element in an array. I have the following code, where you have to manually specify the type, but would like to remove the second argument.

#define ForEach( func, type, list)do {\
    int num_elements = sizeof(list) / sizeof(type);\
    int iter;\
    for( iter = 0; iter < num_elements; iter++)\
        func(list[iter]);\
    }while(0)

void display(int n) {
    printf("\n%d\n", n);
}

int main(void){
    int list [] = { 1,2,3,4,5,6,7,8,9,10};
    ForEach(display, int, list);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70

2 Answers2

3

For the purpose of this question - You can use sizeof operator on elements of the array as -

sizeof(list[0])

If you are using GCC (or anything GNU), there is an extenstion called typeof. You can do

sizeof(typeof(list[0])) 

But the C way of doing it is directly use sizeof the element.

Ajay Brahmakshatriya
  • 8,993
  • 3
  • 26
  • 49
0

I don't believe it is possible. What you can do is instead of

sizeof(type)

do

sizeof(list[0])

But this may not work for malloced arrays.

Read this post

Community
  • 1
  • 1
Archmede
  • 1,592
  • 2
  • 20
  • 37