kalculus said:
Can someone explain what the following code is doing?
void *get_gp_value()
{
void **function_pointer = (void **)get_gp_value;
return function_pointer[1];
}
(which it is indeed doing - it also returns nothing at all useful
on most machines)
OT:
I wonder how the compiler handles
(void*)[1] ... since sizeof void is not defined...
This is a syntax error, even in most non-C-but-kind-of-like-C languages.
Assuming you mean:
void *x = <some valid expression>;
... x[1] ...
Standard C requires a diagnostic.
A number of languages that vaguely resemble, but are not in fact, C,
allow this. What they do depends on the language.
Note that gcc by default implements a language almost but not entirely
unlike C
and you have to tell it to use "-std=c89" (or "-ansi" in
older versions of gcc), or "-std=c99" for C99, and "-pedantic", to
get it to implement Standard C.
Note that:
void **x = ...
... x[1] ...
is very different from:
void *x = ...
... x[1] ...
The former actually means something in C, provided "x" points to the
first of at least two objects of type "void *". For instance, consider
the following somewhat silly code fragment:
int a;
double b;
struct S { char *p; char *q; } c;
void *three_void_stars[3] = { &a, &b, &c };
void **x = three_void_stars;
void *pick(int i) {
return x
;
}
A call to pick() at this point is valid if it supplies an argument
between 0 and 2 inclusive. The value returned is &a, &b, or &c
(converted to "void *"), correspondingly. Thus, we can finish this
code off with:
#include <stdio.h>
int main(int argc, char **argv) {
int *ip;
double *dp;
ip = pick(0);
*ip = 42;
dp = pick(1);
*dp = 4.2;
if (argc > 1)
printf("pick(1): %f\n", *(double *)pick(1));
else
printf("pick(0): %d\n", *(int *)pick(0));
return 0;
}
This program is quite useless, but its output is well-defined.