c - getting at pointers in an array of struct passed as a void* -
i have function signature qsort:
const char* get_str(int i, const void *base, size_t nmemb, size_t size);
i passed arrays of pointers const char*
, or arrays of structs first field pointer const char*
.
what casts need extract pointer in array element i
?
i have tried casting base
array of char itself, can advance right element:
return *(const char**)(((const char*)base)[i * size]);
but compiler complaining: warning: cast pointer integer of different size [-wint-to-pointer-cast]
it looks want implement type or identification sytem structs so:
#include <stdlib.h> #include <stdio.h> struct { const char *id; int x; }; struct b { const char *id; double d; }; union { struct a; struct b b; }; int main() { struct a[] = {{"one", 1}, {"two", 2}, {"three", 3}}; struct b b[] = {{"pi", 3.1415}, {"e", 2.71}}; union any[3]; any[0].a = a[0]; any[1].b = b[0]; any[2].a = a[1]; puts(get_str(1, a, 3, sizeof(*a))); puts(get_str(1, b, 2, sizeof(*b))); puts(get_str(1, any, 3, sizeof(*any))); return 0; }
in case, following works:
const char* get_str(int i, const void *base, size_t nmemb, size_t size) { const char *p = base; const char **pp = (const char**) (p + * size); return *pp; }
this can written in 1 line as:
const char* get_str(int i, const void *base, size_t nmemb, size_t size) { return *(const char**) ((const char *) base + * size); }
but think detour via void pointers not necessary. can address calculations typed array:
puts(*(const char **) (&a[1])); puts(*(const char **) (&b[1])); puts(*(const char **) (&any[1]));
if wrap in function:
const char *get_str(const void *str) { return *(const char **) str; }
you get:
puts(get_str(&a[1])); puts(get_str(&b[1])); puts(get_str(any + 1));
which more readable qsort
ish syntax in opinion.
this works, because acces 1 element @ known position. functions bsort
, qsort
, however, can't use technique, because have access array @ several indices , hence must able index calculation themselves.
Comments
Post a Comment