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);
?
First off, I must make something clear.
float *pandfloat* pare equivalent statements. If you’re a beginner in C, I recommend that you write the latter instead of the former, because it makes clearer what the type is and what the variable is – it will save you a lot of confusion in the future. With that in mind, please remember that in the following blockp, not*p, is the variable.The first line allocates a
float*on the stack. As it happens with all variables allocated on the stack, its initial value is undefined (most probably garbage). This is not exclusive to pointers: even if you allocate anintand you don’t initialize it, it will have an undefined value.The same happens with
p, so you should think ofpas containing random data initially. Ifpcontains random data and it’s a pointer, it means that it’s pointing to a random address. Attempting (in the second line) to write the value1.0f(or anything else) to that random address will almost always cause a segmentation fault, because a random address at any given time has little chance of belonging to your program.