Pointers, definition,use of pointers in self referential structures

shreyassinga1 9 views 82 slides Oct 25, 2025
Slide 1
Slide 1 of 82
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82

About This Presentation

Idea of pointers,
Definition,use of pointers in self referential structures,notation of linked list.
Dynamic memory allocation functions.
String handling functions


Slide Content

1 Topics to be covered Pointers: Idea of pointers, Defining pointers, Use of Pointers in self-referential structures, notation of linked list (no implementation) Dynamic Memory allocation Functions. Strings: String Handling Functions.

2 Pointers: A pointer is a constant or variable that contains an address that can be used to access data There are three concepts associated with the pointers are: Pointer Constants Pointer Values Pointer Variables

3 POINTER CONSTANT The computer’s memory is a sequential collection of ‘storage cells’. Each cell can hold one byte of information, has a unique number associated with it called as ‘address’ We cannot change them, but we can only use them to store data values. These memory addresses are called pointer constants.

4 POINTER VALUE Whenever we declare a variable, the system allocates, an appropriate location to hold the value of the variable somewhere in the memory,. Consider the following declaration, int i=10; This declaration tells the C compiler to perform the following activities: Reserve space in the memory to hold the integer value. Associate the name i with this memory location. Store the value 10 at this location . We can represent i’s location in the memory by the following memory map: 10 i 3217945756 Variable Name Variable value Variable address

5 The & Operator: The address of the variable cannot be accessed directly. The address can be obtained by using address operator (&) in C language The address operator can be used with any variable that can be placed on the left side of an assignment operator. The format specifier of address is %u (unsigned integer),the reason is addresses are always positive values.

6 #include<stdio.h> main() { int *p,a=10; p=&a; printf("a value=%d",a); printf("\np pointer value=%u\n",p); } Example of Pointer value

7 POINTER VARIABLE A variable which holds the address of some other variable is called pointer variable. A pointer variable should contain always the address only. The * Operator It is called as ‘Value at address’ operator. It returns the value stored at a particular address. It is also Known as Indirection or Dereferencing Operator

8 Declaring a pointer variable The syntax for declaring a pointer variable is as follows, data type *ptr_name; This tells the compiler three things about the variable ptr_name. The asterisk (*) tells that the variable ptr_name is a pointer variable. ptr_name needs a memory location. ptr_name points to a variable of type data type. For example: int *pi;

9 Initializing Pointers Once a pointer variable has been declared, it can be made to point to a variable using statement such as ptr_name=&var;  Which cause ptr_name to point to var. Now ptr_name contains the address of var. This is known as pointer initialization. Before a pointer is initialized it should not be used. Access the value of a variable using pointer variable Once a pointer variable has been assigned the address of a variable, we can access the value of a variable using the pointer. This is done by using the indirection operator(*). *ptr_name

10 #include<stdio.h> main() { int i=10; //normal variable int *pi; //pointer variable pi=&i; //i address we are sending to pi variable printf("\noutput\n"); printf("\n The Address of i=%u",&i); printf("\n The Value of i=%d",i); printf("\n The Value of pi=%u",pi); printf("\n The Value of i=%d",*(&i)); printf("\n The Value of i=%d",*pi); printf("\n The Address of pi=%u",&pi); } Example:

11 Declaration versus Redirection An asterisk operator can be used in two different contexts: For declaration and for redirection. Declaration : When an asterisk is used for declaration, it is associated with a type. For example, we define a pointer to an integer as int *p; int *q; Redirection : When used for redirection, the asterisk is an operator that redirects the operation from the pointer variable to a data variable. For example, given two pointers to integers, pa and pb , sum is computed as int sum = *p+ *q;

#include< stdio.h > void main() { // local declarations int a; int b; int c; int *p; int *q; int *r; // statements a=6; b=2; p=&b; q=p; r=&c; p=&a; *q=8; *r=*p; *r=a+*q+*&c; printf (“%d %d % d”,a,b,c ); Printf (“%d %d %d”,*p,*q,*r); 12

13 Add Two Numbers Using Pointers

14 Add Two Numbers Using Pointers

15 Add Two Numbers Using Pointers

16 Demonstrate Pointer Flexibility

17 Using One Pointer for Many Variables

18 Using One Pointer for Many Variables

19 One Variable with Many Pointers

20 Using A Variable with Many Pointers

21 Using A Variable with Many Pointers

Passing arrays as arguments to functions( UNIT-III TOPIC) We can pass array elements as arguments to the called function in two ways 1. pass individual array element at a time. 2. pass the entire array at a time 1. passing individual array elements. we can pass individual array elements to the called functions by either call by value or call by reference. Call by value void main() { int i ; int arr []={10,20,30,40,50}; for( i =0;i<5;i++) display( arr [ i ]); }//main display( int x) { printf (“% d”,x ); }//display Call by reference void main() { int i ; int arr []={10,20,30,40,50}; for( i =0;i<5;i++) display(& arr [ i ]); }//main display( int *x) { printf (“%d”,*x); }//display 22 G.YAMINI IT DEPT

2. pass the entire array at a time Fixed length array- the size of the array is known when the program is written. int arr[10]; Variable length array- the size of the array is known when the program is run. int arr[n]; If u want to pass the fixed length array as argument to the called function, simply pass the array name to called function. void display(int x[]); void main() { int arr[5]={10,20,30,40,50}; display(arr); }//main void display(int x[]) { int i; for(i=0;i<5;i++) { printf(" %d",x[i]); }//for }//display() 23 G.YAMINI IT DEPT

In variable length array we have to pass array name as well as size of the array to the called function. void display( int arr [], int size); void main() { int a[10]; int n,i ; clrscr (); printf ("\n enter the size of the array"); scanf ("% d",&n ); for( i =0;i< n;i ++) scanf ("% d",&a [ i ]); display( a,n ); }//main void display(int arr[],int size) { int i; for(i=0;i<size;i++) printf(" %d",arr[i]); } Note- In c, the name of an array gives the address of the first element in the array 24 G.YAMINI IT DEPT

Def:- Any group of characters defined between double quotation marks is called string String is a sequential collection of character type elements 25 Strings G.Yamini IT DEPT

26 DECLARING AND INITIALIZING STRING VARIABLES Declaring a String: A string variable is a valid C variable name and always declared as an array. The general form of declaration of a string variable is, char string_name [size]; The size determines the number of characters in the string_name . When the compiler assigns a character string to a character array, it automatically supplies a null character(‘\0’) at the end of the string. The size should be equal to the maximum number of characters in the string plus one. G.Yamini IT DEPT

27 DECLARING AND INITIALIZING STRING VARIABLES Initializing a String: This can be done in two ways. 1. char str1[8]=“Welcome”; 2. char str2[8]={‘W’,’e’,’l’,’c’,’o’,’m’,’e’,’\0’}; When the compiler assigns a character string to a character array, it automatically supplies a null character(‘\0’) at the end of the string. The size should be equal to the maximum number of characters in the string plus one G.Yamini IT DEPT

28 Storing Strings and Characters G.Yamini IT DEPT

29 Differences Between Strings and Character Arrays G.Yamini IT DEPT

30 Strings in Arrays G.Yamini IT DEPT

31 Character Literals and String Literals G.Yamini IT DEPT

32 String input and output functions Strings can be read from the keyword and can be displayed onto the monitor using the following I/O functions. Formatted Input Function- scanf () The string can be read using the scanf function also. The format specifier associated with the string is %s. G.Yamini IT DEPT

Note – problem with the scanf () function is that it terminates input on the first white space it finds. so a string with multiple words are not accepted by the string ex- hyderabad snist would not be accepted. 33 STRING INPUT/OUTPUT FUNCTIONS(Contd…) scanf() can be used to read a string with format specifier %s. char name[10]; Scanf(“%s”,name); G.Yamini IT DEPT

void main() { char name[30]; printf(“enter the string”); gets(name); } To read the multiple words of a string use another function gets(). 34 G.Yamini IT DEPT

Writing\ display strings on to a screen We can use printf() function to display string on to a screen with %s format specifier . Printf (“% s”,name ); in this case also printf() function cannot print the multiple words. like hyderabad snist To overcome this problem use puts() to display multiple words. unlike printf() function, puts() places the cursor to the next line. \n is not necessary. 35 G.Yamini IT DEPT

Use puts and gets functions void main() { char name[30]; puts(“enter the string”); gets(name); puts(name); } 36 G.Yamini IT DEPT

The various options associated with printf (): 1. Field width specification 2.Precision specifier 3.Left Justification   1. Field Width Specification   Syntax: %ws  W is the field with specified width. S indicates that the string is being used.   #include< stdio.h > void main () { char s[]=“RAMANANDA”; printf (“%4s\n”, s); printf (“%15s”,s); }     OUTPUT: RAMANANDA RAMANANDA 37 G.Yamini IT DEPT

NOTE: If the string to be printed is larger than the field width w, the entire string will be printed. If the string to be printed is smaller than the field width w, then appropriate number of blank spaces are padded at the beginning of the string so as to ensure that field width w is reached . 38 G.Yamini IT DEPT

2. Precision Specifier  Syntax: %w.ns W is the field specified width N indicates that first n characters have to be displayed. This gives precision. S indicates that the string is being used.   #include< stdio.h > #include< conio.h > void main() { char s []={‘R’,’A’,’M’,’A’,’N’,’A’,’N’,’D’,’A ’,\0}: clrscr (); printf (“%0.2s\ n”,s ); printf (“%9.4s\ n”,s ); printf (“%9.3s\ n”,s ); printf (“%3.5s”,s); getch (); }   RA RAMA RAM RAMAN 39 G.Yamini IT DEPT

40 STRING INPUT/OUTPUT FUNCTIONS( Contd …) NOTE :  The string is printed right justification by default. If w > n, w columns are used to print first n characters .example 2nd and 3rd printf statements. If w < n, minimum n columns are used to print first n characters. Example, 1st and 4th printf statements. G.Yamini IT DEPT

3. Left justification  Syntax: %-w.ns  - just before w indicates that string is printed using left justification. W is the field with specified width. S indicates that the string is being printed. #include< stdio.h > #include< conio.h > void main () { char s []={‘R’,’A’,’M’,’A’,’N’,’A’,’N’,’D’,’A’}: clrscr (); printf (“%-0.2s\n”, s); printf (“%-9.4s\ n”,s ); printf (“%-9.3s\ n”,s ); printf (“%-3.5s”,s); getch (); } OUTPUT: RA RAMA RAM RAMAN 41 G.Yamini IT DEPT

Character I/O from Keyboard To read characters from the keyboard and write to screen it tkas the following form:   variable_name = getchar( ); //reads one character from the keyboard putchar(variable_name); // display the character on the monitor  here variable_name must of type char. 42 G.Yamini IT DEPT

43 String Manipulation Functions The C Library provides a rich set of string handling functions that are placed under the header file < string.h >. Some of the string handling functions are: strlen () strcat () strcpy () strrchr () strcmp ()  strstr () strchr () strrev () Some of the functions in ctype.h file are: toupper () tolower () toascii () G.Yamini IT DEPT

STRING HANDLING FUNCTIONS( Contd …) strlen () function :  This function counts and returns the number of characters in a string. It takes the form Syantax : int n= strlen (string);   Where n is an integer variable, which receives the value of the length of the string. The counting ends at the first null character. 44 G.Yamini IT DEPT

45 G.Yamini IT DEPT

46 STRING HANDLING FUNCTIONS( Contd …) strcmp () function: The strcmp function compares two strings, it returns the value 0 if they are equal. If they are not equal, it returns the numeric difference between the first non matching characters in the strings. It takes the following form: strcmp (str1,str2);   returning value less than 0 means ''str1'' is less than ''str2'‘ returning value 0 means ''str1'' is equal to ''str2'‘ returning value greater than 0 means ''str1'' is greater than ''str2''   string1 and string2 may be string variables or string constants. Example: strcmp (name1,name2); strcmp (name1,”John”); strcmp (“their” ,”there”); G.Yamini IT DEPT

47 String Compares G.Yamini IT DEPT

48 G.Yamini IT DEPT

49 STRING HANDLING FUNCTIONS( Contd …) strcpy () function: It copies the contents of one string to another string. It takes the following form: strcpy (string1,string2);   The above function assign the contents of string2 to string1. string2 may be a character array variable or a string constant. Example: strcpy (city ,”Delhi”); strcpy (city1,city2); strrev () function : Reverses the contents of the string. It takes of the form strrev (string); Example: #include< stdio.h > #include< string.h > void main(){ char s[]=”hello”; strrev (s); puts(s); } G.Yamini IT DEPT

50 String Copy G.Yamini IT DEPT

51 String-number Copy Always use strncpy to copy one string to another. G.Yamini IT DEPT

52 G.Yamini IT DEPT

53 G.Yamini IT DEPT

54 STRING HANDLING FUNCTIONS( Contd …) strstr () function: It is a two-parameter function that can be used to locate a sub-string in a string. It takes the form: strstr (s1, s2); Example: strstr (s1,”ABC”); The function strstr searches the string s1 to see whether the string s2 is contained in s1.If yes, the function returns the position of the first occurrence of the sub-string. Otherwise, it returns a NULL pointer .   strchr () function: It is used to determine the existence of a character in a string. Example: strchr (s1,’m’); //It locates the first occurrence of the character ‘m’. Example: strrchr (s2,’m’); //It locates the last occurrence of the character ‘m’. G.Yamini IT DEPT

55 String in String G.Yamini IT DEPT

56 Character in String ( strchr ) G.Yamini IT DEPT

/*Define functions- length of a string, copy, concatenate, convert into uppercase letters, compare two strings for alphabetical order- over strings and implement in a program*/ #include< stdio.h > #include< string.h > #include< stdlib.h > main() { char str1[15],str2[15]; int n,c,len ; printf ("\n Enter the string1 "); gets(str1); printf ("\n Enter the string2 "); gets(str2); printf ("\n 1. String Length "); printf ("\n 2. String Copy "); printf ("\n 3. String Comparison "); printf ("\n 4. String Concat ") 57 G.Yamini IT DEPT

printf ("\n Enter the choice u want to perform"); scanf ("% d",&n ); switch(n) { case 1: len = strlen (str1); printf ("\n The length of the string entered is % d",len ); break; case 2: strcpy (str1,str2); printf ("\n 1st string =%s,2nd string=%s",str1,str2); break; case 3: c= strcmp (str1,str2); if(c==0) printf ("\n Both are equal"); else printf ("\n Both are different"); break; case 4: printf ("\n The resultant string is: % s",strcat (str1,str2)); break; default: printf ("\n Enter correct choice"); } } G.Yamini IT DEPT

59 Memory Allocation Functions How do you allocate memory for an object? Two techniques used for memory allocation. 1. Static memory allocation 2. Dynamic Memory allocation Memory Usage Static Memory Allocation Dynamic Memory Allocation Memory Allocation Functions Releasing Memory (free) G.Yamini IT DEPT 4/27/2019

60 Memory Allocation G.Yamini IT DEPT 4/27/2019

Memory allocation Methods Memory allocation two types. 1. Static memory allocation 2. Dynamic memory allocation. Static memory allocation- the process of allocating memory during compile time of a program. Dynamic memory allocation- the process of allocating memory during run time of a program. To access data in dynamic memory therefore, we must use a pointer 61 G.Yamini IT DEPT 4/27/2019

4/27/2019 G.Yamini IT DEPT 62 Accessing Dynamic Memory

63 A Conceptual View of Memory Storage area of memory G.Yamini IT DEPT 4/27/2019

There are 4 dynamic memory allocation function which are available in the stdlib.h header file malloc() calloc() realloc() free() malloc(), calloc(), realloc() used for the memory allocation free()- de allocate the memory if it is no longer needed. 64 G.Yamini IT DEPT 4/27/2019

65 Memory Management Functions G.Yamini IT DEPT 4/27/2019

Allocates block memory which contains the number of bytes specified as its parameter It returns a pointer of type void to the first byte of the allocated memory, even the allocated memory is not initialized. This means that we can assign it to any type of pointer. Syntax ptr= (cast-type*)malloc(size); If you want to allocate the memory dynamically to an integer object ptr = ( int *) malloc ( sizeof ( int )); if requested memory is available malloc ( ) returns a pointer which contains the first address of the allocated block of memory. otherwise if the requested memory is not available in the heap malloc () returns NULL values. malloc()- block of memory 66 G.Yamini IT DEPT 4/27/2019

Continuous Memory Allocation ( calloc )multiple block of memory The calloc function is primarily used to allocate memory for arrays. Allocated memory initialized to zero. Remaining all are same as malloc () Ptr=(cast_type*)calloc(n,size); 67 G.Yamini IT DEPT 4/27/2019

3. realloc()- this function is used to alter the size of memory which has been already allocated. syntax realloc(ptr,newsize); 68 G.Yamini IT DEPT 4/27/2019

69 realloc G.Yamini IT DEPT 4/27/2019

70 Releasing of memory (free) When memory locations are allocated by malloc, calloc, or realloc are no longer needed, they should be frees using the predefined function free. It is an error to free memory with a null pointer. It is also a potential error to refer to memory after it has been released. The function declaration statement fo free is shown below: void free (void* ptr); G.Yamini IT DEPT 4/27/2019

71 Freeing Memory The first one releases a single element, allocated with malloc, back to heap and second one releases 200 elements (allocated with calloc) back to heap. Note: It is not the pointers that are being released but rather what they point to. G.Yamini IT DEPT 4/27/2019

Write a C program to find sum of n elements entered by user. // allocate memory dynamically using malloc() function .// #include < stdio.h > #include < stdlib.h > int main() { int num, i , * ptr , sum = 0; printf ("Enter number of elements: "); scanf ("%d", &num); ptr = (* int ) malloc (num * sizeof ( int )); //memory allocated using malloc if( ptr == NULL) { printf ("Error! memory not allocated."); exit(0); } printf ("Enter elements of array: "); for( i = 0; i < num; ++ i ) { scanf ("%d", ptr + i ); sum += *( ptr + i ); } printf ("Sum = %d", sum); free( ptr ); } 4/27/2019 G.Yamini IT DEPT 72

73 Use of Pointers in self-referential structures , Notation of linked list

74 In array, elements are stored in consecutive memory locations. To occupy the adjacent space, block of memory that is required for the array should be allocated before hand. Once memory is allocated, it cannot be extended any more. So that array is called the static data structure . Wastage of memory is more in arrays. Array has fixed size But, Linked list is a dynamic data structure, it is able to grow in size as needed.

75 Dynamic Memory Allocation Dynamic memory allocation Obtain and release memory during execution malloc Takes number of bytes to allocate Use sizeof to determine the size of an object Returns pointer of type void * A void * pointer may be assigned to any pointer If no memory available, returns NULL newPtr = malloc( sizeof( struct node ) ); free Deallocates memory allocated by malloc Takes a pointer as an argument free (newPtr);

76 What is Linked List? A linked list is a linear collection of homogeneous data elements, called nodes, where linear order is maintained by means of links or pointers. Each node has two parts: The first part contains the data (information of the element) and The second part contains the address of the next node (link /next pointer field) in the list. Data part of the link can be an integer, a character, a String or an object of any kind.

77 link data node A Null B C D Start

78 Linked Lists Linked list Linear collection of self-referential structures, called nodes, connected by pointer links. Accessed via a pointer to the first node of the list. Subsequent nodes are accessed via the link-pointer member stored in each node. Link pointer in the last node is set to null to mark the end of list. Data stored dynamically – each node is created as necessary. Length of a list can increase or decrease. Becomes full only when the system has insufficient memory to satisfy dynamic storage allocation requests.

79 Types of linked lists Singly linked list Begins with a pointer to the first node Terminates with a null pointer Only traversed in one direction Circular, singly linked list Pointer in the last node points back to the first node Doubly linked list Two “start pointers”- first element and last element Each node has a forward pointer and a backward pointer Allows traversals both forwards and backwards Circular, doubly linked list Forward pointer of the last node points to the first node and backward pointer of the first node points to the last node

80 Doubly linked list In a singly linked list one can move from the header node to any node in one direction only (left-right). A doubly linked list is a two-way list because one can move in either direction. That is, either from left to right or from right to left. It maintains two links or pointer. Hence it is called as doubly linked list. Where, DATA field - stores the element or data, PREV- contains the address of its previous node, NEXT- contains the address of its next node. PREV DATA NEXT Structure of the node

81 Circular linked list The linked list where the last node points the header node is called circular linked list. Circular singly linked list Circular doubly linked list

82 Self-Referential Structures Self-referential structures Structure that contains a pointer to a structure of the same type Can be linked together to form useful data structures such as lists, queues, stacks and trees Terminated with a NULL pointer (0) Two self-referential structure objects linked together A Null B C D Start