Type conversion with pointers

359 Views Asked by At

I'm at a loss to understand how typecasting works with pointers

double x = 0.7;
int *ptr = (int *)&x;

What is happening with *(byte )&x ? &x means the address of variable x. Then what does typecasting an address mean? Can now ptr also refer to x? And if yes then don't we lose data?

Also what is the size of ptr ?

2

There are 2 best solutions below

5
On BEST ANSWER

Lets refactor your code a little bit:

#include <stdio.h>
#include <stdlib.h>


int main (void)
{
    int i;
    double d = 0.7;
    unsigned char* c = (unsigned char*)&d;

    for (i = 0; i < sizeof(d); i++) {
        printf("%x ", c[i]);
    }

    unsigned int* n = (unsigned int*) &d;

    printf("\n%x", *n);

    return 0;
}

The program above outputs something like this:

$ ./test.exe
66 66 66 66 66 66 e6 3f
66666666

Then what does typecasting an address mean? Can now ptr also refer to x? And if yes then don't we lose data?

Basically what you do is that you take &d which is a double* and convert it to an int*. By doing that you are interpreting whatever resides in memory at the &d into an int. It's not a simple matter of typecasting a double to an int but rather reinterpret the whole memory layout. This may have different outputs on different machines depending on their architecture (32/64 bits) and endianess.

2
On

The line takes the address of the variable x and stores it's value to ptr. You have to cast the assignment because that assignment of double* to int* is not allowed.

By dereferencing ptr after the assignment you violate aliasing rules and cause your program to display undefined behavior.

Size of ptr is equal to the result from sizeof( ptr ) or sizeof( int* ) expression.