1

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.

1
  • *ptr is a char, not a char*. It only makes sense to cast a pointer to char* in order to inspect its contents, and this is the only pointer type that is allowed to alias other pointers (you can use from void* to pass the pointer around, but you cannot inspect its byte representation this way). Casting from char* to other pointers is undefined behavior, if you don't make sure that you are casting to the original pointer that was aliased. And it's completely unclear why you would want to use a char* here, since %d expects an int parameter. Commented Jan 20, 2020 at 9:03

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wooh .. Superb :) I missed that one. Thank so much :B

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.