Memory management in C & C++ is in a linear fashion.
For Example: when the user will declare a variable as
int a=1, b=2, c=3, d=4;
int *p=&d;
cout<<*p<<” “<<&d<<endl; // 4
cout<<*(p+1)<<” “<<&c<<endl; // 3
cout<<*(p+2)<<” “<<&b<<endl; // 2
cout<<*(p+3)<<” “<<&a<<endl; // 1
Basically I want to say when we declare a variable like this .. int a=1, b=2, c=3, d=4;
Then in a memory it stores in the form of 4->3->2->1.
One more example with variables and Array
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a = 12, b = 13, c = 15, p[] = {1, 2, 3}, k = 23;
int *i = &k;
cout << *(i) << " " << &k << "\n";
cout << *(i + 1) << " " << &p[0] << "\n";
cout << *(i + 2) << " " << &p[1] << "\n";
cout << *(i + 3) << " " << &p[2] << "\n";
cout << *(i + 4) << " " << &c << "\n";
cout << *(i + 5) << " " << &b << "\n";
cout << *(i + 6) << " " << &a << "\n";
return 0;
}
[Running] cd "c:\Users\Dipak\Desktop\CPP\arrays&pointers\" && g++ tut1.cpp -o tut1 && "c:\Users\Dipak\Desktop\CPP\arrays&pointers\"tut1
23 0x61fef0
1 0x61fef4
2 0x61fef8
3 0x61fefc
15 0x61ff00
13 0x61ff04
12 0x61ff08
Here is one restriction that we have to use Addresses or print the Addresses of all the variable in program.
To overcome this restriction we can use this :
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a = 1, b = 2, c = 3, d = 4;
int *p = &d;
cout << *p << "\n";
cout << *(p + 1) << "\n";
cout << *(p + 2) << "\n";
cout << *(p + 3) << "\n";
cout << *(p + 4) << "\n";
return 0;
}
output:
[Running] cd "c:\Users\Dipak\Desktop\CPP\arrays&pointers\" && g++ tut3.cpp -o tut3 && "c:\Users\Dipak\Desktop\CPP\arrays&pointers\"tut3
4
6422268
3
2
1
Addresses will be as 4-> (random address) -> 3 -> 2 -> 1
Here on 2nd position the address will be random the rest will be in contiguous manner.