Download presentation
Presentation is loading. Please wait.
1
Chapter 9: Pointers and String
2
Pointer: Definition A pointer is a variable which contains the address in memory of another variable. Through pointers a developer can directly access memory from his/her code which makes memory related operations very fast. But, with great power comes great responsibility.
3
Why Pointers Pointers make the programs simple and reduce their length. Pointers are helpful in allocation and de-allocation of memory during the execution of the program. Thus, pointers are the instruments of dynamic memory management. Pointers enhance the execution speed of a program. Pointers are helpful in traversing through arrays and character strings. Storage of strings through pointers saves memory space. Pointers may be used to pass on arrays, strings, functions, and variables as arguments of a function. Passing on arrays by pointers saves lot of memory because we are passing on only the address of array instead of all the elements of an array, which would mean passing on copies of all the elements and thus taking lot of memory space. Pointers are used to construct different data structures such as linked lists, queues, stacks, etc.
4
Declaring Pointer Variable
Styntax: datatype *pointer name; Example: int *ptr; char *p;
5
The address and indirection operator
Address Operator: & is address operator. Assigns address to pointer variable Eg: int x =10 , *ptr; ptr=&x; Indirection operator * is indirection operator Eg: int x =10 , *ptr, y; y=*ptr;
6
Example 1
7
Pointers as Argument We can pass pointer as argument.
As address is directly passed, this can change the variable value. Calling function should pass address Called function should accept address in pointer Eg: swap(&x,&y); ………………. void swap (int *p, int *q) { ………………….}
8
Example 2
9
Example 3: Finding Largest and smallest Element in array
10
Pointer as return value
Can be used to return value
11
Pointer arithmetic C supports only three forms of pointer arithmetic
Adding an integer to pointer Subtracting an integer from pointer Subtracting one pointer from another
12
Passing array through function Example 4
13
Passing array through function using pointer Example 6
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.