Vishnu CS
Vishnu CS

Reputation: 851

Print Integer value using character pointer in c

I have a small doubt on typecasting. Here I am pasting my sample code.

#include <stdio.h>

int main()
{
    int i=1100;
    char *ptr=(char*)&i;
    
    printf("Value of int =%d\n",(int*)(*ptr));
    return 0;
}

I have typecast at two points. First one is,

char *ptr=(char*)&i;

Second one is ,

printf("Value of int =%d\n",(int*)(*ptr));

in order to avoid the compilation warnings.

When I print it I got the output as

Value of int =76

I know the fact that we need to assign the address of values to the proper type of pointers in order to deference it properly.

My doubt is,

  1. Is it possible to print the value 1100 using character pointer ? If Yes then how ?

I expect a clear cut answer from you folks. Please help on this.

Upvotes: 1

Views: 514

Answers (1)

CoderCharmander
CoderCharmander

Reputation: 1910

In your code, you're casting after it already dereferenced the pointer, so it will just cast a char. Cast the pointer first, like this:

*((int*)ptr)

But still, this is a non-recommended strategy. If you want a really universal pointer type, use void* which will not allow dereferencing while it is not casted.

Upvotes: 1

Related Questions