7. Address Typecasting #
Created Tuesday 24 December 2019
Q) Why don’t we use pointer instead of int*, char* etc. A) We use int* and char* etc to:
- Indicate the jump(or read span) which must be read form the address specified. This is the jump field in the symbol table.
- Interpret the data, even if we know the jump. What is it, Float or Int ? Absurd.
Note: We do have generic pointers(i.e void pointers), but they cannot be derefenced. They need to be cast a data type before dereference.
Q) If a character pointer is assigned the address of an integer with value 65. Is this assignment(of address allowed)? A) Generally this is not valid for addresses. As the lvalue or rvalue jump(depending) on the type may give weird results or out of range behavior.
- Implicit cast, this is done when we are dealing with values. Like char c = ‘65’ or int x = ‘a’ etc.
- Explicit cast, can be used redundantly in case of implicit cast. Especially useful when we want to assign an address of a different pointer type.
char c = ‘a’ int x = (int) &c; Note: when assigning an address to a void pointer, no type-casting is required. Q) Can we assign an a pointer of data_type1, a address of a diffrent type of variable? A) For integer values, most complilers store octets in the reverse order, called the Little Endian System. So 65 is stored as 65 0 0 0. In the Little Endian systemW, the :
- Last bit of the first octet is the LSB.
- First Bit of the last octet is the MSB(aka the sign bit).
- The second octet(from the left in the memory) is the 2nd last octet as written on paper. Similarly for other octets, i.e in the reverse order.
Big Endian stores the number as it is written on a paper(basic math), i.e MSB is the leftmost bit, LSB is the rightmost bit.
- Void pointers can be assigned any address without any typecasting coz, they can are not derefernceable until they are type casted, whch is seperate concern.