If you have a line like this:
u_char variavel_teste
struct teste *p ;
p = (struct teste *)variavel_teste;
What is the use of this, and what does it mean, can you give me an example program?
If you have a line like this:
u_char variavel_teste
struct teste *p ;
p = (struct teste *)variavel_teste;
What is the use of this, and what does it mean, can you give me an example program?
char c = '5';
A char is the size of 1 byte and its address is 0x12345678
.
char *d = &c;
You get the address of c
and save in d
and d
becomes 0x12345678
.
int *e = (int*)d;
You are making your compiler understand that 0x12345678
points to a int
(integer), however, int
is not 1 byte (sizeof(char) != sizeof(int))
, is 4 bytes or 8 according to the architecture.
So when displaying the value of the integer pointer it is considered the first byte that was in c
and the other consecutive bytes that are in the stack is considered garbage for its integer.
Considering this situation it is not advantage to do pointer casting with different types.
Font .
u_char variavel_teste
struct teste *p ;
p = (struct teste *)variavel_teste;
The last line has an error and the compiler has to complain (with error or warning).
What this expression does is to get the value of type u_char
contained in the variable variavel_teste
, convert that value to the corresponding value of type struct teste *
and assign the result of the conversion to p
variable. But there is no correspondence between these two types of values and therefore this conversion is invalid and the compiler has to complain.
Note that cast (explicit conversion) is not strictly necessary because the compiler is forced to automatically convert to compatible type assignments.
Suggestion: Turn on the maximum warnings from your compiler and try to always make clean compilations.