« 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.

pointers_syntax.jpg

Implicit typecasting

1int i = 65;
2char c = i; // implicit typecasting
3cout << "c: " << c << endl;

implicit_casting.jpg

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 *'
4
5
6char *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.

endian_system.jpg

1cout << "p: " << p << endl;
2cout << "pc: " << pc << endl;

p will print the address but pc will print characters until it visits '\0' null character.

int_char_pointer.jpg

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_MIN
11#include <unordered_map>
12using namespace std;
13
14int main()
15{
16 int i = 65;
17 char c = i; // implicit typecasting
18 cout << "c: " << c << endl;
19
20 int *p = &i;
21 char *pc = (char *)p; // explicit typecasting
22
23 cout << "p: " << p << endl;
24 cout << "pc: " << pc << endl;
25
26 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;
31
32 return 0;
33}