« Address typecasting
Understand implicit and explicit typecasting
Pointers syntax
1int * p;2pointer p;
Why do we need to mention int *
for creating a pointer, why can't we simply write pointer
as a data type like int or char.
Because int
in int *
will tell us how to read the 4 bytes available as float also requires 4 bytes and also how many byes
we need to read. Float and in will interpret the same 4 bytes very differently. Thats why even if all pointers store just addresses we still need to mention type.
Implicit typecasting
1int i = 65;2char c = i; // implicit typecasting3cout << "c: " << c << endl;
Copying one type of data type into another data type is called casting. Implicit casting means we don't have to explicitly tell the system to cast, system automatically does it for us.
Explicit typecasting
1int *p = &i;2// char *pc = p;3//error: cannot initialize a variable of type 'char *' with an value of type 'int *'456char *pc = (char *)p; // explicit typecasting
For some cases where typecasting is not obvious, then system throws error. But we can explicitly ask system to proceed with typecasting and system does it for us.
Little endian and Big endian
1cout << "*p: " << *p << endl;2cout << "*pc: " << *pc << endl;3cout << "*(pc+1): " << *(pc + 1) << endl;4cout << "*(pc+2): " << *(pc + 2) << endl;5cout << "*(pc+3): " << *(pc + 3) << endl;
Little endian system means least significant bit is stored first. We might be thinking that (pc+3) will give A as output but pc have A as output as least significant bit is stored first. Most systems are little endian.
1cout << "p: " << p << endl;2cout << "pc: " << pc << endl;
p will print the address but pc will print characters until it visits '\0' null character.
Final code
1#include <iostream>2#include <iomanip>3#include <algorithm>4#include <string>5#include <cstring>6#include <vector>7#include <cmath>8#include <map>9#include <climits>10// climits for INT_MIN11#include <unordered_map>12using namespace std;1314int main()15{16 int i = 65;17 char c = i; // implicit typecasting18 cout << "c: " << c << endl;1920 int *p = &i;21 char *pc = (char *)p; // explicit typecasting2223 cout << "p: " << p << endl;24 cout << "pc: " << pc << endl;2526 cout << "*p: " << *p << endl;27 cout << "*pc: " << *pc << endl;28 cout << "*(pc+1): " << *(pc + 1) << endl;29 cout << "*(pc+2): " << *(pc + 2) << endl;30 cout << "*(pc+3): " << *(pc + 3) << endl;3132 return 0;33}