简体   繁体   中英

don't understand typecasting in C

I've read some of the questions and didn't find what I was looking for. Here is an example of typecasting (I saw it in some video)

    int s = 45;
    double d = *(double *) &s;

(this example is shown to demonstrate how data can be lost if you do this kind of typecasting.) But I can't understand what is the difference between example above and this.

    int s = 45;
    double d = (double) &s;

or this

    int s = 45;
    double d = (double) s;

(double *) &s Means that we are casting the memory address of s as a pointer to a double (since s is actually a double).

(double) &s Means that we are casting the memory address of s as a double which is not correct (the memory address of a variable should be casted as a pointer to that type).

For example:

char s = 'c';
char *s_pointer = (char *)&s;

int t = 1;
int *t_pointer = (int *)&t;

etc,etc

In this example:

int s = 45;
double d = (double) &s;

You take the address of s using & operator , and cast the address itself to double

In the first case:

int s = 45;
double d = *(double *) &s;

You take the address of s using & operator , than you refer to this address as if it pointed a double (double *) &s

Now you have a pointer to a double which is located in the same address where your int is.

using the * operator you take the value in this double pointer .

note that the cast occurs before the de-reference! as if it was:

int s = 45;
double d = *((double *) &s);

We can separate into lines for it to be easier to understand:

int s = 45;
unsigned int addressOfS = &s;
double* pointerToTheSameNumAsPointerToDouble = (double*)addressOfS;
double theValueInThatPointer = *pointerToTheSameNumAsPointerToDouble;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM