[SOLVED] Casting pointer to pointer **p (malloc(sizeof(int*))) to a pointer *p – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by Vaibhav

#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



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


This Question was asked in StackOverflow by Vaibhav and Answered by Vlad from Moscow It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?