I am studying functions that accept arguments of arbitrary datatypes using void pointers. Such a function is the following:
void funct(void *a) {
float *p = a;
printf("number = %f\n",*p);
}
Here is a successful invocation to funct
:
float x = 1.0f;
funct(&x);
x
is declared to be a float and then its pointer, namely &x
(which is of type float*
) is passed to funct
; quite straightforward!
There is however yet another way to declare a variable in C and get its pointer. This is:
float *p;
*p = 1.0f;
But then the call funct(&x);
returns a Segmentation fault: 11
! How is that possible?
Additionally, assume that I want to create a method that accepts a "number" (i.e. float, integer, double, float or anything else (e.g. even u_short)) and adds 1 to it. What would the most versatile implementation possibly be? Should I consider the following prototype:
void add_one(void* x);
?