|
Value int (2's complement) encoding
------------------------------------------------------
.. (1) 00000000 00000000 00000000 00000001
Value IEEE 754 (float) encoding
------------------------------------------------------
.. (1) 01111111 10000000 00000000 00000000
|
int a; a = 2; // will store 00000000 00000000 00000000 00000010 in a |
|
|
Type1 *p;
Type2 *q;
p = (Type1 *) q;
|
meaning:
|
Effect of p = (Type1 *) q is:
|
|
int main(int argc, char *argv[])
{
int i = 1234;
int *p;
/* =====================================================
Read the memory location 4000
===================================================== */
p = (int *) 4000; // Give p the value 4000
printf("Value stored at memory location 4000 = %d\n", *p);
}
|
|
setarch $(uname -m) -R /bin/bash cd ~/demo/c/set2 gcc peek-mem1.c a.out |
|
int a;
float b;
int *p;
p = (int *) &b; // Make C think that p points to an int variable
// Note: &b is (float *) !!!
a = *p; // int = int !!!
// C will not perform conversion !
|
Example:
int a, *p;
float b, *q;
b = 2.0; // b = 01000000000000000000000000000000 !!!
a = b; // C detects type change: performs type conversion to int !
printf("a = %d, b = %f\n", a, b); // Conversion took place (implicitly)
/* ===========================================
How to circumvent C's implicit conversion
=========================================== */
p = (int *)&b; // Make p point to b
a = *p; // Read b as an int typed variable !
printf("a = %d, b = %f\n", a, b); // NO conversion !
|
Output:
a = 2, b = 2.000000 a = 1073741824, b = 2.000000 |
How to run the program:
|