C++ Pointer
Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than actual of data.
Pointer Declaration
data-type *pointer-variable;
data-type * pointer-varaible;
data-type* pointer-varaible;
- Place immediately before pointer-variable.
- Place between the data type and the pointer variable.
- Place immediately after the data type.
int *ptr;
char *ch;
Pointer Initialization
pointer-variable = &variable;
int *ptr,x;
ptr = &x; //initialize
Deference operator (*) and Reference operator (&)
Deference operator (*) gives the value of variable stored at the memory location. Reference operator (&) gives the memory address of a variable. For example: If a number variable is stored in the memory address 0x22, and it contains a value 10. Dereference (*) operator gives the value 10, while reference (&) operator gives the value 0x22.C++ Pointer Example
#include <iostream>
using namespace std;
int main() {
int *ptr, x;
x = 10;
ptr=&x;
cout << "Value of x (x): " << x << endl;
cout << "Value of x at address ptr(*ptr): " << *ptr << endl;
cout << "Address of x (&x): " << &x << endl;
cout << "Address of x that ptr contain (ptr): " << ptr << endl;
*ptr = 5;
cout << "Address of x (&x): " << &x << endl;
cout << "Value of x (x): " << x << endl;
return 0;
}
Value of x (x): 10 Value of x at address ptr(*ptr): 10 Address of x (&x): 0x22fe34 Address of x that ptr contain (ptr): 0x22fe34 Address of x (&x): 0x22fe34 Value of x (x): 5