Doubt pointer cast

Asked

Viewed 582 times

1

Folks when you got a line like this:

u_char variavel_teste
struct teste *p ; 
p = (struct  teste *)variavel_teste; 

What is the use of this , and what it means, can you give me an example of a program?

2 answers

2

char c = '5';

A char has the size of 1 byte and its address is 0x12345678.

char *d = &c;

You get the address of c and keeps in d and d becomes real 0x12345678.

int *e = (int*)d;

You’re making your compiler understand that 0x12345678 points to a int (whole), however, a int is not the size of 1 byte (sizeof(char) != sizeof(int)), is 4 bytes or 8 according to architecture.

So when displaying the value of the whole type pointer is considered the first byte that was in c and the other consecutive bytes that are in the stack (stack) is considered junk for your whole.

Considering this situation it is no advantage to cast pointer with different types.

Source.

1

u_char variavel_teste
struct teste *p ;
p = (struct teste *)variavel_teste; 

The last line has an error and the compiler has to complain (error or Warning).

What this expression does is take the value of type u_char contained in the variable variavel_teste, convert this value to the corresponding value of the type struct teste * and assign the result of the conversation to the variable p. But there is no correspondence between these two types of values and so this conversation is invalid and the compiler has to complain.

Note that the cast (the explicit conversation) is not strictly necessary because the compiler is forced to make the conversation automatically on assignments of compatible types.

Sugestao: turn on as many warnings as possible from your compiler and always try to make clean compilations.

  • pmg plus variable_test becomes a test-type struct?

  • No. the value of variavel_teste is converted (would be, if possible) into a pointer to a type object struct teste.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.