Memory dynamically allocated using malloc is done like this:
int *ptr=(int*)(malloc(sizeof(int)))
I don’t understand why pointer is used before malloc in (int*) and why we have another pointer with int *ptr.
I am sorry to put up this basic question here and bother people here with this one. But I am not clear after googling this and need help.
Thank You.
>Solution :
-
mallocallocates space for anintusingsizeof(int). -
malloc returns a pointer, which is converted to
int *using(int*). -
Finally, it assigns that pointer to
ptr, which could also be written asint* ptr = -
Now
ptrhas the value frommalloc.
There is no difference in
int *ptr=(int*)(malloc(sizeof(int)));
and
int* ptr=(int*)(malloc(sizeof(int)));
but in my opinion, the second one is clearer, because it has the same notation as the cast.
As the commenter said, it can be simplified to:
int* ptr=malloc(sizeof(int));
which, to me, is the clearest and simplest of all. Hope this helps!