odoocms.class.material-5020-material_file
odoocms.class.material-5020-material_file
Address in C++
If we have a variable var in our program, &var will give us its address in the memory.
Example:
#include <iostream>
using namespace std;
int main()
{
// declare variables
int var1 = 3;
int var2 = 24;
int var3 = 17;
As mentioned above, pointers are used to store addresses rather than values.
int *pointVar;
int* pointVar, p;
Here, 5 is assigned to the variable var. And, the address of var is assigned to
the pointVar pointer with the code pointVar = &var.
To get the value pointed by a pointer, we use the * operator. For example:
In the above code, the address of var is assigned to pointVar. We have used the *pointVar to get
the value stored in that address.
Example : Changing Value Pointed by Pointers
#include <iostream>
using namespace std;
int main() {
int var = 5;
int* pointVar;
// store address of var
pointVar = &var;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl
<< endl;
cout << "Changing value of var to 7:" << endl;
// change value of var to 7
var = 7;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl
<< endl;
cout << "Changing value of *pointVar to 16:" << endl;
// change value of var to 16
*pointVar = 16;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl;
return 0;
}
Output : ????
int *ptr;
int arr[5];
#include <iostream>
using namespace std;
int main()
{
float arr[3];
// ptr = &arr[0]
ptr = arr;
return 0;
}
In the above program, we first simply printed the addresses of the array elements
without using the pointer variable ptr.
Then, we used the pointer ptr to point to the address of a[0], ptr + 1 to point to the
address of a[1], and so on.
#include <iostream>
using namespace std;
int main() {
float arr[5];
return 0;
}
We first used the pointer notation to store the numbers entered by the user into the array arr.
Notice that we haven't declared a separate pointer variable, but rather we are using the
array name arr for the pointer notation.
As we already know, the array name arr points to the first element of the array. So, we
can think of arr as acting like a pointer.
Similarly, we then used for loop to display the values of arr using pointer notation.