Search code examples
cpointerstypecasting-operator

Type casting the character pointer


I am from Java back ground.I am learning C in which i gone through a code snippet for type conversion from int to char.

int a=5;
int *p;
p=&a;
char *a0;
a0=(char* )p;

My question is that , why we use (char *)p instead of (char)p.

We are only casting the 4 byte memory(Integer) to 1 byte(Character) and not the value related to it


Solution

  • You need to consider pointers as variable that contains addresses. Their sole purpose is to show you where to look in the memory.

    so consider this:

    int a = 65;
    void* addr = &a;
    

    now the 'addr' contains the address of the the memory where 'a' is located what you do with it is up to you.

    here I decided to "see" that part of the memory as an ASCII character that you could print to display the character 'A'

    char* car_A = (char*)addr;
    putchar(*car_A); // print: A (ASCII code for 'A' is 65)
    

    if instead you decide to do what you suggested:

    char* a0 = (char)addr;
    
    • The left part of the assignment (char)addr will cast a pointer 'addr' (likely to be 4 or 8 bytes) to a char (1 byte)

    • The right part of the assignment, the truncated address, will be assigned as the address of the pointer 'a0'

    If you don't see why it doesn't make sense let me clarify with a concrete example

    Say the address of 'a' is 0x002F4A0E (assuming pointers are stored on 4 bytes) then

    • '*addr' is equal to 65
    • 'addr' is equal to 0x002F4A0E

    When casting it like so (char)addr this become equal to 0x0E. So the line

    char* a0 = (char)addr;
    

    become

    char* a0 = 0x0E
    

    So 'a0' will end up pointing to the address 0x0000000E and we don't know what is in this location.

    I hope this clarify your problem