Session 8

| Pointers Session 8 Objectives Explain what a pointer is and where it is used Explain how to use pointer variables and pointer operators Assign values to pointers Explain pointer arithmetic Explain pointer comparisons Explain pointers and single dimensional arrays Explain Pointer and multidimensional arrays Explain how allocation of memory takes place What is a Pointer? A pointer is a variable, which contains the address of a memory location of another variable If one variable contains the address of another variable, the first variable is said to point to the second variable A pointer provides an indirect method of accessing the value of a data item Pointers can point to variables of other fundamental data types like int, char, or double or data aggregates like arrays or structures What are Pointers used for? Some situations where pointers can be used are - To return more than one value from a function To pass arrays and strings more conveniently from one function to another To manipulate arrays easily by moving pointers to them instead of moving the arrays itself To allocate memory and access it (Direct Memory Allocation) Pointer Variables A pointer declaration consists of a base type and a variable name preceded by an * General declaration syntax is : For Example: type *name; int *var2; Pointer Operators There are 2 special operators which are used with pointers : The & operator is a unary operator and it returns the memory address of the operand The second operator * is the complement of &. It is a unary operator and returns the value contained in the memory location pointed to by the pointer variable’s value and & * var2 = &var1; temp = *var2; Assigning Values To Pointers-1 Values can be assigned to pointers through the & operator. Here the address of var is stored in the variable ptr_var It is also possible to assign values to pointers through another pointer variable pointing to a data item of the same data type ptr_var = &var; ptr_var = &var; ptr_var2 = .

4    3    0    19-06-2021
6    4    0    19-06-2021
2    3    0    19-06-2021
6    3    0    19-06-2021