Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I don't understand pointers in dynamic memory allocation

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank You.

>Solution :

  1. malloc allocates space for an int using sizeof(int).

  2. malloc returns a pointer, which is converted to int * using (int*).

  3. Finally, it assigns that pointer to ptr, which could also be written as

    int* ptr =

  4. Now ptr has the value from malloc.

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading