| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [View Raw Code] [Original HTTPS Page] |
Pointer is a variable which holds the memory information(address) of another variable of same data type.
Pointer's data type should match with the data type of the variable which is getting pointed.
datatype* pointername;
// or
datatype *pointername;#include <iostream>
using namespace std;
int main()
{
int num = 10;
int *ptr; // pointer variable
ptr = #
cout << "Value of the variable: " << *ptr;
cout << "\nValue at the address: " << ptr;
return 0;
}#include <iostream>
using namespace std;
int main()
{
int x = 10, *ptr;
/*ptr = x; // Error because ptr is adress and x is value
*ptr = &x; // Error because x is adress and ptr is value */
ptr = &x; // valid because &x and ptr are addresses
*ptr = x; // valid because both x and *ptr values
cout << "Value of *ptr: " << *ptr << endl;
cout << "Value of &x: " << &x << endl;
cout << "Value of ptr: " << ptr << endl;
cout << "Value of x: " << x << endl;
}Pointes has the ability to store address of more than one elements or a cells of elements.
#include <iostream>
using namespace std;
int main()
{
int arr[3] = { 2, 3, 4 }; // arr is an array of size 3
int* ptr = arr; // syntax for making a pointer point to an array
cout << ptr << endl; //prints the address of arr[0] beacuse ptr stores the address of the first element of arr
cout << *ptr << endl; //prints the value of the first element i.e, 2
//Now let us see how can we print the whole array by using the pointer
for (int i = 0; i < 3; i++){
cout << *(ptr + i) << endl;
}
return 0;
}| Back | FazBrowse Home | New Git URL |