C++ 39: Pointers
Variables:
- The Variable is a memory location with specified name.
- Every memory location has a unique address That means every variable have unique address.
- The variable is used to store values.
Pointers
- The pointer is variable which can be used to store address of a variable or memory location or an object.
- The pointer always points to the memory location or object whoose address is currently present in the pointer.
- The pointers are mainly used to reserve and releze the memory dynamically (i.e during runtime at the execution of the program).
- Also, pointers are used to perform following operations.
- To pass array as argument
- To return multiple values from a function
- A pointer can be defined using syntax:
Syntax :
data_type *poiter_name;
Storing address of a variable in the pointer:
- The "address_of" (i.e. &) operator returns the address of the varable.
- The address of variable is unsigned integer(i.e. the address cannot be negative) so, to print the address we have to use the format specifier %u in C programming.
- The address of the variable can be stored in the pointer by using following syntax:
- Syntax:
- pointer_variable = &variable;
Example:
#include <iostream>using namespace std;int main(){int a = 5;int *p = &a; //pointer variablecout << "a = " << a << endl;cout << "*p = " << p << endl;(*p)++;cout << "a = " << a << endl;cout << "*p = " << *p << endl;return 0;}
Output:
a = 5
*p = 0x61fe14
a = 6
*p = 6Example 2:
#include <iostream>
using namespace std;main(){ int a = 5, b = 10, *p, *q;
p = &a; q = &b;
int x = *p + *q;
cout << " p = " << p << endl; cout << " q = " << q << endl; cout << "*p = " << *p << endl; cout << "*q = " << *q << endl;
cout << "x = " << x << endl; int y = *p * *q; cout << "y = " << y << endl; return 0;}Output:
p = 0x61fe04
q = 0x61fe00
*p = 5
*q = 10
x = 15
y = 50Example 3:
#include <iostream>
using namespace std;main(){ int a = 2, *p, *q; p = &a; q = p;
cout << a << "\t" << *p << "\t" << *q << endl; a++; (*p)++; (*q)*= 2;
cout << a << "\t" << *p << "\t" << *q << endl; return 0;}Output:
2 2 2
8 8 8
Comments
Post a Comment