简体   繁体   中英

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?

在此处输入图像描述

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

malloc knows nothing about types, it only cares about the size.

The correct incantations are

T *t = malloc(sizeof(*t)); // or
T *t = malloc(sizeof(T));

If you pass any other expression to malloc and it by sheer coincidence happens to have the correct value, you get lucky and nothing bad happens. But this is confusing. Do not confuse the readers of your code.

If the value passed to malloc is greater than the correct one, you just waste memory. If it is less, you risk Undefined Behaviour.

It is implementation defined whether sizeof(int) is the same as, larger than, or smaller than sizeof(int*) so just don't do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM