Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What actually happens when a pointer to integer is cast to a pointer to char?

Tags:

c

casting

int i=40;
char *p;
p=(char *)&i;//What actually happens here?
printf("%d",*p);

What will be the output? Please help!

like image 296
vas Avatar asked Sep 20 '10 06:09

vas


People also ask

What happens when you cast a pointer to an int?

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

What happens when you cast a pointer?

A pointer is an arrow that points to an address in memory, with a label indicating the type of the value. The address indicates where to look and the type indicates what to take. Casting the pointer changes the label on the arrow but not where the arrow points.

What does casting to char * do?

Typecasting is a way to make a variable of one type, such as an int, act like another type, such as a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable.

Why pointer convert from one type to another is prohibited in C?

Conversion of an integer into a pointer to a function is also permitted by The Standard. However, both are prohibited by this rule in order to avoid the undefined behaviour that would result from calling a function using an incompatible pointer type.


1 Answers

p=(char *)&i;//What actually happens here?

It takes the address of i and casts it to a char pointer. So the value of *p is now the first byte of i. What that value is, is platform dependent.

like image 160
sepp2k Avatar answered Nov 16 '22 01:11

sepp2k