Pointer Basics,Constant Pointers & Pointer to Constant.
The document discusses the basics of pointers, including their declaration, how to access the value they point to using dereferencing, and the concept of pointers to pointers. It also covers the use of pointers as function parameters and the distinction between constant pointers and pointers to constant. The differences between constant pointers and pointers to constant are highlighted, including their ability to be modified and incremented.
POINTERS • A pointeris a variable that points a address of a variable. • A pointer is declared using the * operator before an identifier.
3.
Declaration ofPointer variables : type *pointer_name; where type is the type of data pointed to For example :- int *numberPointer;
4.
ADDRESS (&) OPERATOR Pointer address operator is denoted by ‘&’ symbol The & is a unary operator that returns the memory address of its operand. Example : &n - It gives an address on variable n
5.
DEREFERENCING OPERATOR (*) We can access to the value stored in the variable pointed to by using the dereferencing operator (*) Syntax: *PointerVariable Example: int V = 101; int *P = &V;
6.
POINTERS TO POINTERS A pointer to a pointer is a chain of pointers. In pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value. Pointer Pointer Variable Address Address Value
7.
Declaration of pointerto a pointer : int **ptr; For example : // local declaration int a; int *p; int **q; // Statment a=58; p=&a; q=&p;
POINTERS AS PARAMETERS To make changes to a variable that exist after a function ends, we pass the address of the variable to the function For example : #include<iostream.h> void Indirectswap(char *ptr1, char *ptr2) { char c = *ptr1; *ptr1 = *ptr2; *ptr2 = c; }
10.
int main() { char a= ‘y’; char b = ‘n’; Indirectswap(&a,&b); cout<< a << “and”<< b << endl; return 0; } OUTPUT n and y
Constant pointer Constantpointer cannot be modified. Modification in integer to which it points to it is allowed. Syntax: int n1=20; int *const ptr=&n1; //Declare constant
Pointer to constant Pointer to constant object is called as pointer to constant object. Syntax: int n=30; const int *ptr=&n; “const int” means integer constant. We cannot change value of integer. We can change address of such pointer so that it will point to new memory allocation
Difference Constant pointer Pointerto constant Pointer can be incremented. Pointer is not incremented. Constant pointer is pointing to data object. Pointer is pointing to constant data object.t Declaration :int * const ptr; Declaration: const int *ptr;