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

Casting pointer to pointer **p (malloc(sizeof(int*))) to a pointer *p

#include<stdio.h>
#include<stdlib.h>
int main() {
    int *n = malloc(sizeof(int*));//line 1
    scanf("%d",n);
    printf("%d",*n);
}

I am not sure what is happening here.
Does line 1 (in the snippet above) mean n now simply is a pointer to an int?
And we have started using the memory allocated for a pointer as variable itself?
Is the pointer to pointer cast to pointer to int?

enter image description here

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

>Solution :

In this line

int *n = malloc(sizeof(int*));//line 1

you allocated memory of the size equal to sizeof( int * ) and its address is assigned to the pointer n having the type int *.

So using this pointer to access the memory it is interpreted as a memory storing an object of the type int

scanf("%d",n);
printf("%d",*n);

Actually the kind of the argument expression used to specify the size of the allocated memory is not very important. For example you could just write

int *n = malloc( 8 );//line 1
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