syntax for malloc without specifying the type of variable

advertisements

I have seen on the web the following syntax to use malloc :

double ***x;
x = malloc(N * sizeof(*x));
for (i = 0; i < size_y; i++) {
   x[i] = malloc(N * sizeof(**x));

i.e, the type of variable which is pointed, is not specified into malloc : usually, we declare pointer like this :

double ***x;
x = malloc(N * sizeof(double*));
for (i = 0; i < size_y; i++) {
   x[i] = malloc(N * sizeof(double**));

From what I have understood, the first method allows to quiclky changing the type pointed just by replacing the "double ***x" by "int ***x" for example.

In the second method, we have to replace all "double" by "int" into sizeof

Is this first method valid and if yes, is it recommended ?

Thanks for your help


Is it valid? Yes (in principle). The sizeof operator can apply to a type (as in your second example), or equally it can apply to any expression (returning the size of the type returned by that expression). So it is valid. I say "in principle" because you are passing the wrong expression to the wrong malloc call, though.

Is it recommended? Well, I would recommend it for the reasons you've already stated.