1+ /*
2+ Pointers
3+ - Pointer is a variable that stores the address of another variable
4+ Syntax: datatype * variable_name
5+ - The size of pointer doesn't depend upon datatype. It is same for all.
6+ */
7+
8+ #include < iostream>
9+ using namespace std ;
10+
11+ int main (){
12+ int a = 10 ;
13+ int b = 20 ;
14+ cout << " &a: " << &a << endl;
15+ cout << " &b: " << &b << " \n\n " ;
16+
17+ int *p = &a; // declaration + initializaton
18+ int *pt; // declaration [currently storing garbage value]
19+
20+ /*
21+ Sometimes it is useful to make our pointers point to nothing. This is called a null pointer.
22+ We assign a pointer a null value by setting it to address 0.
23+ */
24+ int *ptr = 0 ; // NULL pointer
25+
26+ // store the address of variable a
27+ ptr = &a; // assignment
28+ cout << " ptr: " << ptr << endl;
29+
30+ // Re-assign another address to ptr pointer
31+ ptr = &b;
32+ cout << " ptr: " << ptr << endl;
33+
34+ return 0 ;
35+ }
36+
37+ /*
38+ OUTPUT:
39+
40+ &a: 0x7fff1ce2db00
41+ &b: 0x7fff1ce2db04
42+
43+ ptr: 0x7fff1ce2db00
44+ ptr: 0x7fff1ce2db04
45+
46+
47+ More About Pointers:
48+
49+ - Pointer & Arithmetic
50+ > Addition, Multiplication, Division of two addresses doesn’t make any sense
51+ > Addition of an address by a constant integer value
52+ i.e. ptr +5 means address of cell which is 5 * sizeof(*ptr) away from ptr.
53+ > Similar for subtraction
54+ > Again Multiplying/Dividing an address with some constant value doesn’t make any sense
55+ > Subtracting two address of same type would give you number of elements between them
56+
57+ - Arrays & Pointers
58+ > An Array is actually a pointer that points to the first element of the array!
59+ Because the array variable is a pointer, you can dereference it, which returns array element 0.
60+ > a[i] is same as *(a + i)
61+
62+ - Difference – Arrays & Pointers
63+ - The sizeof operator
64+ > sizeof(array) returns the amount of memory used by all elements in array
65+ > sizeof(pointer) only returns the amount of memory used by the pointer variable itself
66+
67+ - The & operator
68+ > &array is an alias for &array[0] and returns the address of the first element in array
69+ > &pointer returns the address of pointer
70+
71+ - String literal initialization of a character array
72+ > char array[] = “abc” sets the first four elements in array to ‘a’, ‘b’, ‘c’, and ‘\0′
73+ > char *pointer = “abc” sets pointer to the address of the “abc” string
74+ (which may be stored in read-only memory and thus unchangeable)
75+
76+ - Assignment/Re-assigment
77+ > Pointer variable can be assigned a value whereas array variable cannot be.
78+ Eg: int a[10];
79+ int *p;
80+ p=a; // legal
81+ a=p; // illegal
82+
83+ - Arithmetic
84+ > Arithmetic on pointer variable is allowed but array can’t be incremented/decremented.
85+ Eg: p++; // legal
86+ a++; // illegal
87+ */
0 commit comments