Last article covered typecasting of variable. The same is extended here for pointers. It is highly recommended to re-read article on pointers and endianess. Here we discuss what are different pointer typecasting that can done, which makes functional sense, which of typecasting should be avoided.
Generally pointers of same type should be always assigned with each other. If pointers have to stored or passed to some other function they can be casted to and from void pointer. Note that de-reference of the void pointer is not valid.
int *pi; char *pc; float *pf; void *pv; pv = (void*)pi; //OK pc = (char*)pi; //NOK pf = (float*)pi; //NOK
Even though there is sax error with NOK
it highly recommended no to do that way. It is functionally flawed usage, even though syntactically fine. Type casting of to and from void pointer need not be done at all; we could directly use it as follows.
pv = pi; // No need of typecast here
If we use typecasting between different type of pointer, compiler generally gives up warning.
pc = pi; // This generates warning
a.c:9:7: warning: assignment from \ incompatible pointer type \ [-Wincompatible-pointer-types] pc = pi; // This generates warning ^
Same things can be extended other type of pointers such as struct pointer, union pointer, function pointer so on.
Links
- Next Article - C Programming #72: Strings
- Previous Article - C Programming #70: Typecasting Variable
- All Article - C Programming
No comments :
Post a Comment