SlideShare a Scribd company logo
In this session, you will learn to: Declare and manipulate pointers Use pointers to manipulate character arrays Objectives
Every stored data item occupies one or more contiguous memory cells. Every cell in the memory has a unique address. Any reference to a variable, declared in memory, accesses the variable through the address of memory location. Pointers are variables, which contain the addresses of other variables (of any data type) in memory. Declaring and Manipulating Pointers
A pointer variable must be declared before use in a program. A pointer variable is declared preceded by an asterisk. The declaration:   int *ptr; /* ptr is pointing to an int */ Indicates that  ptr  is a pointer to an integer variable. An uninitialized pointer may potentially point to any area of the memory and can cause a program to crash. A pointer can be initialized as follows: ptr= &x; In the preceding initialization, the pointer  ptr  is pointing to  x . Declaring Pointers
In the following declaration: float *ptr_to_float; The pointer variable  ptr_to_float  is pointing to a variable of type ____________. 2.  Is the following declaration valid?  *ptr_to_something; 3.  State whether True or False:    An integer is declared In the following declaration:  int *ptr_to_int;  4.  Is the following declaration valid? int some_int, *ptr_to_int;  Practice: 4.1
Solution: 1. float 2. No. When a pointer variable is being declared, the type of variable to which it is pointing to ( int ,  float , or  char ) should also be indicated. 3. False. A pointer to an integer is being declared and not an integer. 4. Yes. It is okay to club declaration of a certain type along with pointers to the same type. Practice: 4.1 (Contd.)
Pointers can be manipulated like variables. The unary operator * gives value of the variable a pointer is pointing to. The unary operator * is also termed as the indirection operator. The indirection operator can be used only on pointers. Manipulating Pointers
The symbol _________ is used to obtain the address of a variable while the symbol__________ is used to obtain the value of the variable to which a pointer is pointing to. With the following declarations:  int x, y, *ptr; Which of the following are meaningful assignments? a. x = y; b. y=*ptr; c. x = ptr; d. x = &.ptr; e. ptr = &x; f. x = &y; Practice: 4.2
3. Consider the following sequence of statements and complete the partially-filled table: int x, y, *ptrl, *ptr2;  x = 65;  y = 89; ptr1 = &x; /*ptrl points to x */ ptr2 = &y/; /* ptr2 points to y */ x = *ptr1; /* statement A*) ptr1 = ptr2: /* statement B */ x = *ptr1; /* statement C*/ After statement &x  x  &y   y  ptr1 ptr2 A 1006   1018 B C Practice: 4.2 (Contd.)
4.  What is the output of the following sequence of statements: int x, y, temp,*ptrl, *ptr2;  /* declare */ x = 23; y = 37; ptrl = &x; /* ptrl points to x */ ptr2 = &y; /* ptr2 points to y */ temp = *ptrl; *ptr1 = *ptr2; *ptr2 = temp; printf(“x is %d while y is %d”, x, y); Practice: 4.2 (Contd.)
Solution: Practice: 4.2 (Contd.)
Pointer Arithmetic: Arithmetic operations can be performed on pointers. Therefore, it is essential to declare a pointer as pointing to a certain datatype so that when the pointer is incremented or decremented, it moves by the appropriate number of bytes. Consider the following statement: ptr++; It does not necessarily mean that  ptr  now points to the next memory location. The memory location it will point to will depend upon the datatype to which the pointer points.  May be initialized when declared if done outside  main() . Consider the following example: #include <stdio.h> char movie[]= “Jurassic Park”; main() { char *ptr; Pointer Arithmetic
Consider the following example: #include <stdio.h> char movie[]= “Jurassic Park”; main() { char *ptr; ptr=movie; printf(“%s”, movie); /* output: Jurassic Park */ printf(“%s”,ptr); /* output: Jurassic Park */ ptr++; printf(“%s”,movie); /* output: Jurassic Park */ printf(“%s&quot;,prr); /* output: urassic Park */ ptr++; printf(“%s”,movie); /* output; Jurassic Park */ printf(“%s”,ptr); /* output: rassic Park */ /* Note that the incrementing of the pointer ptr does not in any way affect the pointer movie */ } Pointer Arithmetic (Contd.)
Consider the following code snippet: #include <stdio.h>  int one_d[] = {l,2,3};  main(){ int *ptr; ptr = one_d; ptr +=3; /* statement A*/ printf(“%d\n”, *ptr); /*statement B */ } After statement A is executed, the new address of  ptr  will be ____ bytes more than the old address . State whether True or False: The statement B will print 3 .  Practice: 4.3
Solution: 12 ( Size of integer = 4*3) False. Note that  ptr  is now pointing past the one-d array. So, whatever is stored (junk or some value) at this address is printed out. Again, note the dangers of arbitrary assignments to pointer variables. Practice: 4.3 (Contd.)
Array name contains the address of the first element of the array. A pointer is a variable, which can store the address of another variable. It can be said that an array name is a pointer. Therefore, a pointer can be used to manipulate an array. Using Pointers to Manipulate Character Arrays
One-Dimensional Arrays and Pointers: Consider the following example: #include <stdio.h> char str[13]={“Jiggerypokry”}; char strl[]={ “Magic”}; main() {   char *ptr;   printf(“We are playing around with %s&quot;, str); /* Output: We are playing around with Jiggerypokry*/ ptr=str ; /* ptr now points to whatever str is pointing to */ printf(“We are playing around with %s&quot; ,ptr); /* Output: We are playing around with Jiggerypokry */ } One-Dimensional Arrays and Pointers
In the preceding example the statement: ptr=str;  Gives the impression that the two pointers are equal. However, there is a very subtle difference between  str  and  ptr .  str  is a static pointer, which means that the address contained in  str  cannot be changed. While  ptr  is a dynamic pointer. The address in  ptr  can be changed. One-Dimensional Arrays and Pointers  (Contd.)
Given the declaration: char some_string [10]; some_string  points to _________. State whether True or False: In the following declaration, the pointer  err_msg  contains a valid address: char *err_msg = “Some error message”; 3. State whether True or False: Consider the following declaration: char *err_msg = “Some error message”; It is more flexible than the following declaration:  char err_msg[19]=”Some error message”; Practice: 4.4
Solution: 1. some_string [0] 2. True  3. True. Note that one does not have to count the size of the error message in the first declaration. Practice: 4.4 (Contd.)
Two-dimensional arrays can be used to manipulate multiple strings at a time. String manipulation can also be done by using the array of pointers, as shown in the following example: char *things[6];  /* declaring an array of 6 pointers to char */   things[0]=”Raindrops on roses”; things[1]=”And Whiskers on kettles”; things[2]=”Bright copper kettles”; things[3]=”And warm woolen mittens”; things[4]=”Brown paper packages tied up with strings”; things[5]=”These are a few of my favorite things”; Two-Dimensional Arrays and Pointers
The third line of the song can be printed by the following statement: printf(“%s”, things[2]); /*Output: Bright copper kettles */ Two-Dimensional Arrays and Pointers (Contd.)
State whether True or False: While declaring two-dimensional character arrays using pointers, yon do not have to go through the tedium of counting the number of characters in the longest string. 2. Given the following error messages: All's well File not found  No read permission for file Insufficient memory  No write permission for file Write a program to print all the error messages on screen, using pointers to array. Practice: 4.5
Solution: True. New strings can be typed straight away within the {}. As in: char *err_msg_msg[]= { “ All's well”, “ File not found”,  “ No read permission for file”, “ Insufficient memory”,  “ No write permission for file” }; The number of strings will define the size of the array.  Practice: 4.5 (Contd.)
2. The program is: # include<stdio.h>  # define ERRORS 5  char *err_msg[]= { /*Note the missing index*/ “ All's well”, “ File not found”,  “ No read permission for file”, “ Insufficient memory”,  “ No write permission for file” }; main() { int err_no; for ( err_no = 0; err_no < ERRORS; err_no++ ) { printf ( “\nError message %d is : %s\n”, err_no + 1, err_msg[err_no]); } } Practice: 4.5 (Contd.)
Consider the following two-d array declaration: int num[3][4]= { {3, 6, 9, 12}, {15, 25, 30, 35}, {66, 77, 88, 99} }; This statement actually declares an array of 3 pointers (constant)  num[0] ,  num[l] , and  num[2]  each containing the address of the first element of three single-dimensional arrays. The name of the array,  num , contains the address of the first element of the array of pointers (the address of  num[0] ). Here, *num  is equal to  num[0]  because  num[0]  points to  num[0][0] . *(*num)  will give the value 3. *num  is equal to  num[0] . Two-Dimensional Arrays and Pointers (Contd.)
Pointers can be used to write string-handling functions. Consider the following examples: /* function to calculate length of a string*/ #include <stdio.h> main() { char *ptr, str[20]; int size=0; printf(“\nEnter string:”); gets(str); fflush(stdin); for(ptr=str ; *ptr != '\0'; ptr++) { size++; } printf(“String length is %d”, size); } String-Handling Functions Using Pointers
/*function to check for a palindrome */ # include <stdio.h> main() { char str[50],*ptr,*lptr; printf(“\nEnter string :”); gets(str); fflush(stdin); for(lptr=str; *lptr !=’\0'; lptr++);  /*reach the string terminator */ lptr--; /*position on the last character */ for(ptr=str; ptr<=lptr; lptr--,ptr++) { if(*ptr != *lptr) break;} if(ptr>lptr) printf(“%s is a palindrome” ); else printf(“%s is not a palindrome&quot;); } Using Pointers to Manipulate Character Arrays (Contd.)
In this session, you learned that: A pointer is a variable, which contains the address of some other variable in memory. A pointer may point to a variable of any data type. A pointer can point to any portion of the memory. A pointer variable is declared as: datatype *<pointer variable name> A pointer variable is initialized as: pointer variable name> = &<variable name to which the pointer will point to> The  &  returns the address of the variable. The  *  before a pointer name gives the value of the variable to which it is pointing. Summary
Pointers can also be subjected to arithmetic. Incrementing a pointer by 1 makes it point to a memory location given by the formula: New address = Old address + Scaling factor One-dimensional character arrays can be declared by declaring a pointer and initializing it. The name of a character array is actually a pointer to the first element of the array. Two-dimensional character arrays can also be declared by using pointers. Summary (Contd.)
Ad

More Related Content

What's hot (20)

Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
Functions-Computer programming
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programming
nmahi96
 
Computer programming(CP)
Computer programming(CP)Computer programming(CP)
Computer programming(CP)
nmahi96
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdfUSER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
MomenMostafa
 
C programming & data structure [character strings & string functions]
C programming & data structure   [character strings & string functions]C programming & data structure   [character strings & string functions]
C programming & data structure [character strings & string functions]
MomenMostafa
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013
srikanthreddy004
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
KALAISELVI P
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
Vikram Nandini
 
C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
Vijayananda Mohire
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
K Durga Prasad
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
Icaii Infotech
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
 
Structures-2
Structures-2Structures-2
Structures-2
arshpreetkaur07
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1
Prerna Sharma
 
C# String
C# StringC# String
C# String
Raghuveer Guthikonda
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
ShivanshuVerma11
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
Functions-Computer programming
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programming
nmahi96
 
Computer programming(CP)
Computer programming(CP)Computer programming(CP)
Computer programming(CP)
nmahi96
 
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdfPOINTERS IN C MRS.SOWMYA JYOTHI.pdf
POINTERS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdfUSER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
MomenMostafa
 
C programming & data structure [character strings & string functions]
C programming & data structure   [character strings & string functions]C programming & data structure   [character strings & string functions]
C programming & data structure [character strings & string functions]
MomenMostafa
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013
srikanthreddy004
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
KALAISELVI P
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
Vikram Nandini
 
C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
Vijayananda Mohire
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
K Durga Prasad
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
Icaii Infotech
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1
Prerna Sharma
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
ShivanshuVerma11
 

Viewers also liked (13)

C programming session 03
C programming session 03C programming session 03
C programming session 03
Dushmanta Nath
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)
Dushmanta Nath
 
Dacj 1-2 c
Dacj 1-2 cDacj 1-2 c
Dacj 1-2 c
Niit Care
 
Java script session 3
Java script session 3Java script session 3
Java script session 3
Saif Ullah Dar
 
Session no 2
Session no 2Session no 2
Session no 2
Saif Ullah Dar
 
Session no 4
Session no 4Session no 4
Session no 4
Saif Ullah Dar
 
Session No1
Session No1 Session No1
Session No1
Saif Ullah Dar
 
C programming session 11
C programming session 11C programming session 11
C programming session 11
Dushmanta Nath
 
C programming session 07
C programming session 07C programming session 07
C programming session 07
Dushmanta Nath
 
Niit
NiitNiit
Niit
Mahima Narang
 
Java script Session No 1
Java script Session No 1Java script Session No 1
Java script Session No 1
Saif Ullah Dar
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
Fahim Abdullah
 
Session 3 Java Script
Session 3 Java ScriptSession 3 Java Script
Session 3 Java Script
Muhammad Hesham
 
C programming session 03
C programming session 03C programming session 03
C programming session 03
Dushmanta Nath
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)
Dushmanta Nath
 
Dacj 1-2 c
Dacj 1-2 cDacj 1-2 c
Dacj 1-2 c
Niit Care
 
Java script session 3
Java script session 3Java script session 3
Java script session 3
Saif Ullah Dar
 
C programming session 11
C programming session 11C programming session 11
C programming session 11
Dushmanta Nath
 
C programming session 07
C programming session 07C programming session 07
C programming session 07
Dushmanta Nath
 
Java script Session No 1
Java script Session No 1Java script Session No 1
Java script Session No 1
Saif Ullah Dar
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
Fahim Abdullah
 
Session 3 Java Script
Session 3 Java ScriptSession 3 Java Script
Session 3 Java Script
Muhammad Hesham
 
Ad

Similar to C programming session 05 (20)

C programming session 07
C programming session 07C programming session 07
C programming session 07
Vivek Singh
 
Arrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptxArrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptx
Ramakrishna Reddy Bijjam
 
Pointers in C
Pointers in CPointers in C
Pointers in C
Vijayananda Ratnam Ch
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
Md. Imran Hossain Showrov
 
Pointers
PointersPointers
Pointers
Prasadu Peddi
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
Vikram Nandini
 
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejejeUnit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
KathanPatel49
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
Hemantha Kulathilake
 
C pointers and references
C pointers and referencesC pointers and references
C pointers and references
Thesis Scientist Private Limited
 
Introduction to pointers in c plus plus .
Introduction to pointers in c plus plus .Introduction to pointers in c plus plus .
Introduction to pointers in c plus plus .
karimibaryal1996
 
Pointer in C
Pointer in CPointer in C
Pointer in C
bipchulabmki
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
ajajkhan16
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
Mohammed Saleh
 
Pointers
PointersPointers
Pointers
Vardhil Patel
 
Pointers in C++ object oriented programming
Pointers in C++ object oriented programmingPointers in C++ object oriented programming
Pointers in C++ object oriented programming
Ahmad177077
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
janithlakshan1
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
sai tarlekar
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
NewsMogul
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
TamiratDejene1
 
Pointers
PointersPointers
Pointers
PreethyJemima
 
C programming session 07
C programming session 07C programming session 07
C programming session 07
Vivek Singh
 
Arrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptxArrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptx
Ramakrishna Reddy Bijjam
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
Vikram Nandini
 
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejejeUnit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
KathanPatel49
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
Hemantha Kulathilake
 
Introduction to pointers in c plus plus .
Introduction to pointers in c plus plus .Introduction to pointers in c plus plus .
Introduction to pointers in c plus plus .
karimibaryal1996
 
Pointer in C
Pointer in CPointer in C
Pointer in C
bipchulabmki
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
ajajkhan16
 
Pointers in C++ object oriented programming
Pointers in C++ object oriented programmingPointers in C++ object oriented programming
Pointers in C++ object oriented programming
Ahmad177077
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
sai tarlekar
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
NewsMogul
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
TamiratDejene1
 
Ad

More from Dushmanta Nath (6)

Global Warming Project
Global Warming ProjectGlobal Warming Project
Global Warming Project
Dushmanta Nath
 
DBMS Practical File
DBMS Practical FileDBMS Practical File
DBMS Practical File
Dushmanta Nath
 
Manufacturing Practice (MP) Training Project
Manufacturing Practice (MP) Training ProjectManufacturing Practice (MP) Training Project
Manufacturing Practice (MP) Training Project
Dushmanta Nath
 
BSNL Training Project
BSNL Training ProjectBSNL Training Project
BSNL Training Project
Dushmanta Nath
 
IT- 328 Web Administration (Practicals)
IT- 328 Web Administration (Practicals)IT- 328 Web Administration (Practicals)
IT- 328 Web Administration (Practicals)
Dushmanta Nath
 
IT-314 MIS (Practicals)
IT-314 MIS (Practicals)IT-314 MIS (Practicals)
IT-314 MIS (Practicals)
Dushmanta Nath
 
Global Warming Project
Global Warming ProjectGlobal Warming Project
Global Warming Project
Dushmanta Nath
 
DBMS Practical File
DBMS Practical FileDBMS Practical File
DBMS Practical File
Dushmanta Nath
 
Manufacturing Practice (MP) Training Project
Manufacturing Practice (MP) Training ProjectManufacturing Practice (MP) Training Project
Manufacturing Practice (MP) Training Project
Dushmanta Nath
 
BSNL Training Project
BSNL Training ProjectBSNL Training Project
BSNL Training Project
Dushmanta Nath
 
IT- 328 Web Administration (Practicals)
IT- 328 Web Administration (Practicals)IT- 328 Web Administration (Practicals)
IT- 328 Web Administration (Practicals)
Dushmanta Nath
 
IT-314 MIS (Practicals)
IT-314 MIS (Practicals)IT-314 MIS (Practicals)
IT-314 MIS (Practicals)
Dushmanta Nath
 

Recently uploaded (20)

Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 

C programming session 05

  • 1. In this session, you will learn to: Declare and manipulate pointers Use pointers to manipulate character arrays Objectives
  • 2. Every stored data item occupies one or more contiguous memory cells. Every cell in the memory has a unique address. Any reference to a variable, declared in memory, accesses the variable through the address of memory location. Pointers are variables, which contain the addresses of other variables (of any data type) in memory. Declaring and Manipulating Pointers
  • 3. A pointer variable must be declared before use in a program. A pointer variable is declared preceded by an asterisk. The declaration: int *ptr; /* ptr is pointing to an int */ Indicates that ptr is a pointer to an integer variable. An uninitialized pointer may potentially point to any area of the memory and can cause a program to crash. A pointer can be initialized as follows: ptr= &x; In the preceding initialization, the pointer ptr is pointing to x . Declaring Pointers
  • 4. In the following declaration: float *ptr_to_float; The pointer variable ptr_to_float is pointing to a variable of type ____________. 2. Is the following declaration valid? *ptr_to_something; 3. State whether True or False: An integer is declared In the following declaration: int *ptr_to_int; 4. Is the following declaration valid? int some_int, *ptr_to_int; Practice: 4.1
  • 5. Solution: 1. float 2. No. When a pointer variable is being declared, the type of variable to which it is pointing to ( int , float , or char ) should also be indicated. 3. False. A pointer to an integer is being declared and not an integer. 4. Yes. It is okay to club declaration of a certain type along with pointers to the same type. Practice: 4.1 (Contd.)
  • 6. Pointers can be manipulated like variables. The unary operator * gives value of the variable a pointer is pointing to. The unary operator * is also termed as the indirection operator. The indirection operator can be used only on pointers. Manipulating Pointers
  • 7. The symbol _________ is used to obtain the address of a variable while the symbol__________ is used to obtain the value of the variable to which a pointer is pointing to. With the following declarations: int x, y, *ptr; Which of the following are meaningful assignments? a. x = y; b. y=*ptr; c. x = ptr; d. x = &.ptr; e. ptr = &x; f. x = &y; Practice: 4.2
  • 8. 3. Consider the following sequence of statements and complete the partially-filled table: int x, y, *ptrl, *ptr2; x = 65; y = 89; ptr1 = &x; /*ptrl points to x */ ptr2 = &y/; /* ptr2 points to y */ x = *ptr1; /* statement A*) ptr1 = ptr2: /* statement B */ x = *ptr1; /* statement C*/ After statement &x x &y y ptr1 ptr2 A 1006 1018 B C Practice: 4.2 (Contd.)
  • 9. 4. What is the output of the following sequence of statements: int x, y, temp,*ptrl, *ptr2; /* declare */ x = 23; y = 37; ptrl = &x; /* ptrl points to x */ ptr2 = &y; /* ptr2 points to y */ temp = *ptrl; *ptr1 = *ptr2; *ptr2 = temp; printf(“x is %d while y is %d”, x, y); Practice: 4.2 (Contd.)
  • 11. Pointer Arithmetic: Arithmetic operations can be performed on pointers. Therefore, it is essential to declare a pointer as pointing to a certain datatype so that when the pointer is incremented or decremented, it moves by the appropriate number of bytes. Consider the following statement: ptr++; It does not necessarily mean that ptr now points to the next memory location. The memory location it will point to will depend upon the datatype to which the pointer points. May be initialized when declared if done outside main() . Consider the following example: #include <stdio.h> char movie[]= “Jurassic Park”; main() { char *ptr; Pointer Arithmetic
  • 12. Consider the following example: #include <stdio.h> char movie[]= “Jurassic Park”; main() { char *ptr; ptr=movie; printf(“%s”, movie); /* output: Jurassic Park */ printf(“%s”,ptr); /* output: Jurassic Park */ ptr++; printf(“%s”,movie); /* output: Jurassic Park */ printf(“%s&quot;,prr); /* output: urassic Park */ ptr++; printf(“%s”,movie); /* output; Jurassic Park */ printf(“%s”,ptr); /* output: rassic Park */ /* Note that the incrementing of the pointer ptr does not in any way affect the pointer movie */ } Pointer Arithmetic (Contd.)
  • 13. Consider the following code snippet: #include <stdio.h> int one_d[] = {l,2,3}; main(){ int *ptr; ptr = one_d; ptr +=3; /* statement A*/ printf(“%d\n”, *ptr); /*statement B */ } After statement A is executed, the new address of ptr will be ____ bytes more than the old address . State whether True or False: The statement B will print 3 . Practice: 4.3
  • 14. Solution: 12 ( Size of integer = 4*3) False. Note that ptr is now pointing past the one-d array. So, whatever is stored (junk or some value) at this address is printed out. Again, note the dangers of arbitrary assignments to pointer variables. Practice: 4.3 (Contd.)
  • 15. Array name contains the address of the first element of the array. A pointer is a variable, which can store the address of another variable. It can be said that an array name is a pointer. Therefore, a pointer can be used to manipulate an array. Using Pointers to Manipulate Character Arrays
  • 16. One-Dimensional Arrays and Pointers: Consider the following example: #include <stdio.h> char str[13]={“Jiggerypokry”}; char strl[]={ “Magic”}; main() { char *ptr; printf(“We are playing around with %s&quot;, str); /* Output: We are playing around with Jiggerypokry*/ ptr=str ; /* ptr now points to whatever str is pointing to */ printf(“We are playing around with %s&quot; ,ptr); /* Output: We are playing around with Jiggerypokry */ } One-Dimensional Arrays and Pointers
  • 17. In the preceding example the statement: ptr=str; Gives the impression that the two pointers are equal. However, there is a very subtle difference between str and ptr . str is a static pointer, which means that the address contained in str cannot be changed. While ptr is a dynamic pointer. The address in ptr can be changed. One-Dimensional Arrays and Pointers (Contd.)
  • 18. Given the declaration: char some_string [10]; some_string points to _________. State whether True or False: In the following declaration, the pointer err_msg contains a valid address: char *err_msg = “Some error message”; 3. State whether True or False: Consider the following declaration: char *err_msg = “Some error message”; It is more flexible than the following declaration: char err_msg[19]=”Some error message”; Practice: 4.4
  • 19. Solution: 1. some_string [0] 2. True 3. True. Note that one does not have to count the size of the error message in the first declaration. Practice: 4.4 (Contd.)
  • 20. Two-dimensional arrays can be used to manipulate multiple strings at a time. String manipulation can also be done by using the array of pointers, as shown in the following example: char *things[6]; /* declaring an array of 6 pointers to char */ things[0]=”Raindrops on roses”; things[1]=”And Whiskers on kettles”; things[2]=”Bright copper kettles”; things[3]=”And warm woolen mittens”; things[4]=”Brown paper packages tied up with strings”; things[5]=”These are a few of my favorite things”; Two-Dimensional Arrays and Pointers
  • 21. The third line of the song can be printed by the following statement: printf(“%s”, things[2]); /*Output: Bright copper kettles */ Two-Dimensional Arrays and Pointers (Contd.)
  • 22. State whether True or False: While declaring two-dimensional character arrays using pointers, yon do not have to go through the tedium of counting the number of characters in the longest string. 2. Given the following error messages: All's well File not found No read permission for file Insufficient memory No write permission for file Write a program to print all the error messages on screen, using pointers to array. Practice: 4.5
  • 23. Solution: True. New strings can be typed straight away within the {}. As in: char *err_msg_msg[]= { “ All's well”, “ File not found”, “ No read permission for file”, “ Insufficient memory”, “ No write permission for file” }; The number of strings will define the size of the array. Practice: 4.5 (Contd.)
  • 24. 2. The program is: # include<stdio.h> # define ERRORS 5 char *err_msg[]= { /*Note the missing index*/ “ All's well”, “ File not found”, “ No read permission for file”, “ Insufficient memory”, “ No write permission for file” }; main() { int err_no; for ( err_no = 0; err_no < ERRORS; err_no++ ) { printf ( “\nError message %d is : %s\n”, err_no + 1, err_msg[err_no]); } } Practice: 4.5 (Contd.)
  • 25. Consider the following two-d array declaration: int num[3][4]= { {3, 6, 9, 12}, {15, 25, 30, 35}, {66, 77, 88, 99} }; This statement actually declares an array of 3 pointers (constant) num[0] , num[l] , and num[2] each containing the address of the first element of three single-dimensional arrays. The name of the array, num , contains the address of the first element of the array of pointers (the address of num[0] ). Here, *num is equal to num[0] because num[0] points to num[0][0] . *(*num) will give the value 3. *num is equal to num[0] . Two-Dimensional Arrays and Pointers (Contd.)
  • 26. Pointers can be used to write string-handling functions. Consider the following examples: /* function to calculate length of a string*/ #include <stdio.h> main() { char *ptr, str[20]; int size=0; printf(“\nEnter string:”); gets(str); fflush(stdin); for(ptr=str ; *ptr != '\0'; ptr++) { size++; } printf(“String length is %d”, size); } String-Handling Functions Using Pointers
  • 27. /*function to check for a palindrome */ # include <stdio.h> main() { char str[50],*ptr,*lptr; printf(“\nEnter string :”); gets(str); fflush(stdin); for(lptr=str; *lptr !=’\0'; lptr++); /*reach the string terminator */ lptr--; /*position on the last character */ for(ptr=str; ptr<=lptr; lptr--,ptr++) { if(*ptr != *lptr) break;} if(ptr>lptr) printf(“%s is a palindrome” ); else printf(“%s is not a palindrome&quot;); } Using Pointers to Manipulate Character Arrays (Contd.)
  • 28. In this session, you learned that: A pointer is a variable, which contains the address of some other variable in memory. A pointer may point to a variable of any data type. A pointer can point to any portion of the memory. A pointer variable is declared as: datatype *<pointer variable name> A pointer variable is initialized as: pointer variable name> = &<variable name to which the pointer will point to> The & returns the address of the variable. The * before a pointer name gives the value of the variable to which it is pointing. Summary
  • 29. Pointers can also be subjected to arithmetic. Incrementing a pointer by 1 makes it point to a memory location given by the formula: New address = Old address + Scaling factor One-dimensional character arrays can be declared by declaring a pointer and initializing it. The name of a character array is actually a pointer to the first element of the array. Two-dimensional character arrays can also be declared by using pointers. Summary (Contd.)

Editor's Notes

  • #2: Begin the session by explaining the objectives of the session.
  • #4: Pointers contain addresses of variables of a specific type. Hence, the pointer and the variable to which it is pointing should be of the same type. The number of bytes used by the pointer to hold an address does not depend on the type of the variable the variable it is pointing to. The number of bytes used by a pointer is generally 4 bytes, or 2 bytes in some implementations. Type casting may be used to initialize a pointer with the address of a variable of a different type. For example, the following code is valid : char *ptr ; int i = 4 ; ptr = (char *) (&amp;i) ; though this is seldom done. Pointers to type void can contain addresses of any data. It does not make sense to do any arithmetic with these pointers.
  • #5: Use this slide to test the student’s understanding on declaring pointers.
  • #7: Preceding a pointer with ampersand will yield the address of the pointer itself, and can be stored in a pointer to a pointer. Consider the following code: char *ptr, **pptr, chr; ptr = &amp;chr; /* address of a character */ pptr = &amp;ptr; /* address of a pointer */
  • #8: Use this slide to test the student’s understanding on declaring and initializing pointers.
  • #12: Generally, only the operators + and – are used with pointers. This results in the address in the pointer getting altered by a value equal to the size of the data type it is associated with. The following declaration is for a pointer to an array of 10 elements: char (*ptr) [10] ; /* note, it is not an array of pointers */ If the pointer ptr is initialized and contains the address 100 , ptr++ results in the address in ptr being scaled by 10. ptr will now contain 110.
  • #14: Use this slide to test the student’s understanding on pointers arithmetic.
  • #19: Use this slide to test the student’s understanding on one-dimensional arrays and pointers.
  • #23: Use this slide to test the student’s understanding on 2-D arrays and pointers.
  • #29: Use this and the next slide to summarize the session.