Subject OOP Topic Pointer Pointer Pointer is a
Subject: OOP Topic: Pointer
Pointer • Pointer is a variable in C++ that holds the address of another variable. • They have data type just like variables, for example an integer type pointer can hold the address of an integer variable and an character type pointer can hold the address of char variable.
Pointer • Pointers are symbolic representation of addresses. • They enable programs to simulate call-byreference as well as to create and manipulate dynamic data structures. It’s general declaration in C/C++ has the format: • Syntax: datatype *var_name; int *ptr;
Work of Pointer
How to use a pointer? • Define a pointer variable • Assigning the address of a variable to a pointer using unary operator (&) which returns the address of that variable. • Accessing the value stored in the address using unary operator (*) which returns the value of the variable located at the address specified by its operand. • The reason we associate data type to a pointer is that it knows how many bytes the data is stored in. When we increment a pointer, we increase the pointer by the size of data type to which it points.
Show with Diagram
Example-1 • • • // C++ program to illustrate Pointers in C++ #include <stdio. h> void geeks() { int var = 20; // declare pointer variable int *ptr; ptr = &var;
Example-1 • • • // assign the pointer printf("Value } // Driver program int main() { geeks(); } address of a variable to a at ptr = %p n", ptr); at var = %d n", var); at *ptr = %d n", *ptr);
Example-1 • • Output: Value at ptr = 0 x 7 ffcb 9 e 9 ea 4 c Value at var = 20 Value at *ptr = 20
- Slides: 9