SlideShare uma empresa Scribd logo
1 de 29
Slide 1 of 29Ver. 1.0
Programming in C
In this session, you will learn to:
Declare and manipulate pointers
Use pointers to manipulate character arrays
Objectives
Slide 2 of 29Ver. 1.0
Programming in C
Declaring and Manipulating Pointers
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.
Slide 3 of 29Ver. 1.0
Programming in C
Declaring 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.
Slide 4 of 29Ver. 1.0
Programming in C
Practice: 4.1
1. 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;
Slide 5 of 29Ver. 1.0
Programming in C
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.)
Slide 6 of 29Ver. 1.0
Programming in C
Manipulating Pointers
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.
Slide 7 of 29Ver. 1.0
Programming in C
Practice: 4.2
1. 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.
2. 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;
Slide 8 of 29Ver. 1.0
Programming in C
Practice: 4.2 (Contd.)
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
Slide 9 of 29Ver. 1.0
Programming in 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);
Slide 10 of 29Ver. 1.0
Programming in C
Solution:
Practice: 4.2 (Contd.)
Microsoft Office
Word 97 - 2003 Document
Slide 11 of 29Ver. 1.0
Programming in C
Pointer Arithmetic
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;
Slide 12 of 29Ver. 1.0
Programming in C
Pointer Arithmetic (Contd.)
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",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 */
}
Slide 13 of 29Ver. 1.0
Programming in C
Practice: 4.3
1. 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(“%dn”, *ptr); /*statement B */
}
a. After statement A is executed, the new address of ptr will be
____ bytes more than the old address.
b. State whether True or False:
The statement B will print 3.
Slide 14 of 29Ver. 1.0
Programming in C
Solution:
a. 12 ( Size of integer = 4*3)
b. 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.)
Slide 15 of 29Ver. 1.0
Programming in C
Using Pointers to Manipulate Character Arrays
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.
Slide 16 of 29Ver. 1.0
Programming in C
One-Dimensional Arrays and Pointers
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", 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" ,ptr);
/* Output: We are playing around with Jiggerypokry */
}
Slide 17 of 29Ver. 1.0
Programming in C
One-Dimensional Arrays and Pointers (Contd.)
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.
Slide 18 of 29Ver. 1.0
Programming in C
Practice: 4.4
1. Given the declaration:
char some_string [10];
some_string points to _________.
1. 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”;
Slide 19 of 29Ver. 1.0
Programming in C
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.)
Slide 20 of 29Ver. 1.0
Programming in C
Two-Dimensional Arrays and Pointers
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”;
Slide 21 of 29Ver. 1.0
Programming in C
Two-Dimensional Arrays and Pointers (Contd.)
The third line of the song can be printed by the following
statement:
printf(“%s”, things[2]);
/*Output: Bright copper kettles */
Slide 22 of 29Ver. 1.0
Programming in C
Practice: 4.5
1. 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.
Slide 23 of 29Ver. 1.0
Programming in C
Solution:
1. 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.)
Slide 24 of 29Ver. 1.0
Programming in C
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 : %sn”, err_no +
1, err_msg[err_no]); } }
Practice: 4.5 (Contd.)
Slide 25 of 29Ver. 1.0
Programming in C
Two-Dimensional Arrays and Pointers (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].
Slide 26 of 29Ver. 1.0
Programming in C
String-Handling Functions Using Pointers
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);
}
Slide 27 of 29Ver. 1.0
Programming in C
Using Pointers to Manipulate Character Arrays (Contd.)
/*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");
}
Slide 28 of 29Ver. 1.0
Programming in C
Summary
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.
Slide 29 of 29Ver. 1.0
Programming in C
Summary (Contd.)
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.

Mais conteúdo relacionado

Mais procurados

Pointers in c
Pointers in cPointers in c
Pointers in c
Mohd Arif
 
Lecturer23 pointersin c.ppt
Lecturer23 pointersin c.pptLecturer23 pointersin c.ppt
Lecturer23 pointersin c.ppt
eShikshak
 

Mais procurados (20)

C programming - Pointer and DMA
C programming - Pointer and DMAC programming - Pointer and DMA
C programming - Pointer and DMA
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
Lecture 17 - Strings
Lecture 17 - StringsLecture 17 - Strings
Lecture 17 - Strings
 
C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
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]
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Introduction to pointers and memory management in C
Introduction to pointers and memory management in CIntroduction to pointers and memory management in C
Introduction to pointers and memory management in C
 
C pointer
C pointerC pointer
C pointer
 
Lecturer23 pointersin c.ppt
Lecturer23 pointersin c.pptLecturer23 pointersin c.ppt
Lecturer23 pointersin c.ppt
 
Pointer in c
Pointer in c Pointer in c
Pointer in c
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
 
Advanced+pointers
Advanced+pointersAdvanced+pointers
Advanced+pointers
 

Semelhante a C programming session 07

C programming session 05
C programming session 05C programming session 05
C programming session 05
Vivek Singh
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
Vivek Singh
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
Dushmanta Nath
 

Semelhante a C programming session 07 (20)

C programming session 05
C programming session 05C programming session 05
C programming session 05
 
Lesson 9. Pattern 1. Magic numbers
Lesson 9. Pattern 1. Magic numbersLesson 9. Pattern 1. Magic numbers
Lesson 9. Pattern 1. Magic numbers
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
About size_t and ptrdiff_t
About size_t and ptrdiff_tAbout size_t and ptrdiff_t
About size_t and ptrdiff_t
 
Python Guide.pptx
Python Guide.pptxPython Guide.pptx
Python Guide.pptx
 
Lesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmeticLesson 13. Pattern 5. Address arithmetic
Lesson 13. Pattern 5. Address arithmetic
 
C –FAQ:
C –FAQ:C –FAQ:
C –FAQ:
 
C programming session8
C programming  session8C programming  session8
C programming session8
 
C programming session8
C programming  session8C programming  session8
C programming session8
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Development of a static code analyzer for detecting errors of porting program...
Development of a static code analyzer for detecting errors of porting program...Development of a static code analyzer for detecting errors of porting program...
Development of a static code analyzer for detecting errors of porting program...
 
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
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
Pointers
PointersPointers
Pointers
 
Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)Let's us c language (sabeel Bugti)
Let's us c language (sabeel Bugti)
 
PSPC--UNIT-2.pdf
PSPC--UNIT-2.pdfPSPC--UNIT-2.pdf
PSPC--UNIT-2.pdf
 
C Programming Intro.ppt
C Programming Intro.pptC Programming Intro.ppt
C Programming Intro.ppt
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 

Mais de Vivek Singh

C programming session 14
C programming session 14C programming session 14
C programming session 14
Vivek Singh
 
C programming session 13
C programming session 13C programming session 13
C programming session 13
Vivek Singh
 
C programming session 11
C programming session 11C programming session 11
C programming session 11
Vivek Singh
 
C programming session 10
C programming session 10C programming session 10
C programming session 10
Vivek Singh
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
Vivek Singh
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
Vivek Singh
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
Vivek Singh
 
C programming session 16
C programming session 16C programming session 16
C programming session 16
Vivek Singh
 
Niit aptitude question paper
Niit aptitude question paperNiit aptitude question paper
Niit aptitude question paper
Vivek Singh
 
Excel shortcut and tips
Excel shortcut and tipsExcel shortcut and tips
Excel shortcut and tips
Vivek Singh
 
Sql where clause
Sql where clauseSql where clause
Sql where clause
Vivek Singh
 
Sql update statement
Sql update statementSql update statement
Sql update statement
Vivek Singh
 
Sql tutorial, tutorials sql
Sql tutorial, tutorials sqlSql tutorial, tutorials sql
Sql tutorial, tutorials sql
Vivek Singh
 
Sql select statement
Sql select statementSql select statement
Sql select statement
Vivek Singh
 
Sql query tuning or query optimization
Sql query tuning or query optimizationSql query tuning or query optimization
Sql query tuning or query optimization
Vivek Singh
 
Sql query tips or query optimization
Sql query tips or query optimizationSql query tips or query optimization
Sql query tips or query optimization
Vivek Singh
 
Sql order by clause
Sql order by clauseSql order by clause
Sql order by clause
Vivek Singh
 
Sql operators comparision & logical operators
Sql operators   comparision & logical operatorsSql operators   comparision & logical operators
Sql operators comparision & logical operators
Vivek Singh
 

Mais de Vivek Singh (20)

C programming session 14
C programming session 14C programming session 14
C programming session 14
 
C programming session 13
C programming session 13C programming session 13
C programming session 13
 
C programming session 11
C programming session 11C programming session 11
C programming session 11
 
C programming session 10
C programming session 10C programming session 10
C programming session 10
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
 
C programming session 16
C programming session 16C programming session 16
C programming session 16
 
Niit aptitude question paper
Niit aptitude question paperNiit aptitude question paper
Niit aptitude question paper
 
Excel shortcut and tips
Excel shortcut and tipsExcel shortcut and tips
Excel shortcut and tips
 
Sql where clause
Sql where clauseSql where clause
Sql where clause
 
Sql update statement
Sql update statementSql update statement
Sql update statement
 
Sql tutorial, tutorials sql
Sql tutorial, tutorials sqlSql tutorial, tutorials sql
Sql tutorial, tutorials sql
 
Sql subquery
Sql subquerySql subquery
Sql subquery
 
Sql select statement
Sql select statementSql select statement
Sql select statement
 
Sql rename
Sql renameSql rename
Sql rename
 
Sql query tuning or query optimization
Sql query tuning or query optimizationSql query tuning or query optimization
Sql query tuning or query optimization
 
Sql query tips or query optimization
Sql query tips or query optimizationSql query tips or query optimization
Sql query tips or query optimization
 
Sql order by clause
Sql order by clauseSql order by clause
Sql order by clause
 
Sql operators comparision & logical operators
Sql operators   comparision & logical operatorsSql operators   comparision & logical operators
Sql operators comparision & logical operators
 

Último

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Último (20)

ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 

C programming session 07

  • 1. Slide 1 of 29Ver. 1.0 Programming in C In this session, you will learn to: Declare and manipulate pointers Use pointers to manipulate character arrays Objectives
  • 2. Slide 2 of 29Ver. 1.0 Programming in C Declaring and Manipulating Pointers 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.
  • 3. Slide 3 of 29Ver. 1.0 Programming in C Declaring 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.
  • 4. Slide 4 of 29Ver. 1.0 Programming in C Practice: 4.1 1. 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;
  • 5. Slide 5 of 29Ver. 1.0 Programming in C 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. Slide 6 of 29Ver. 1.0 Programming in C Manipulating Pointers 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.
  • 7. Slide 7 of 29Ver. 1.0 Programming in C Practice: 4.2 1. 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. 2. 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;
  • 8. Slide 8 of 29Ver. 1.0 Programming in C Practice: 4.2 (Contd.) 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
  • 9. Slide 9 of 29Ver. 1.0 Programming in 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);
  • 10. Slide 10 of 29Ver. 1.0 Programming in C Solution: Practice: 4.2 (Contd.) Microsoft Office Word 97 - 2003 Document
  • 11. Slide 11 of 29Ver. 1.0 Programming in C Pointer Arithmetic 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;
  • 12. Slide 12 of 29Ver. 1.0 Programming in C Pointer Arithmetic (Contd.) 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",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 */ }
  • 13. Slide 13 of 29Ver. 1.0 Programming in C Practice: 4.3 1. 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(“%dn”, *ptr); /*statement B */ } a. After statement A is executed, the new address of ptr will be ____ bytes more than the old address. b. State whether True or False: The statement B will print 3.
  • 14. Slide 14 of 29Ver. 1.0 Programming in C Solution: a. 12 ( Size of integer = 4*3) b. 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. Slide 15 of 29Ver. 1.0 Programming in C Using Pointers to Manipulate Character Arrays 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.
  • 16. Slide 16 of 29Ver. 1.0 Programming in C One-Dimensional Arrays and Pointers 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", 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" ,ptr); /* Output: We are playing around with Jiggerypokry */ }
  • 17. Slide 17 of 29Ver. 1.0 Programming in C One-Dimensional Arrays and Pointers (Contd.) 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.
  • 18. Slide 18 of 29Ver. 1.0 Programming in C Practice: 4.4 1. Given the declaration: char some_string [10]; some_string points to _________. 1. 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”;
  • 19. Slide 19 of 29Ver. 1.0 Programming in C 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. Slide 20 of 29Ver. 1.0 Programming in C Two-Dimensional Arrays and Pointers 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”;
  • 21. Slide 21 of 29Ver. 1.0 Programming in C Two-Dimensional Arrays and Pointers (Contd.) The third line of the song can be printed by the following statement: printf(“%s”, things[2]); /*Output: Bright copper kettles */
  • 22. Slide 22 of 29Ver. 1.0 Programming in C Practice: 4.5 1. 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.
  • 23. Slide 23 of 29Ver. 1.0 Programming in C Solution: 1. 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. Slide 24 of 29Ver. 1.0 Programming in C 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 : %sn”, err_no + 1, err_msg[err_no]); } } Practice: 4.5 (Contd.)
  • 25. Slide 25 of 29Ver. 1.0 Programming in C Two-Dimensional Arrays and Pointers (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].
  • 26. Slide 26 of 29Ver. 1.0 Programming in C String-Handling Functions Using Pointers 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); }
  • 27. Slide 27 of 29Ver. 1.0 Programming in C Using Pointers to Manipulate Character Arrays (Contd.) /*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"); }
  • 28. Slide 28 of 29Ver. 1.0 Programming in C Summary 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.
  • 29. Slide 29 of 29Ver. 1.0 Programming in C Summary (Contd.) 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.

Notas do Editor

  1. Begin the session by explaining the objectives of the session.
  2. 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.
  3. Use this slide to test the student’s understanding on declaring pointers.
  4. 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 */
  5. Use this slide to test the student’s understanding on declaring and initializing pointers.
  6. 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.
  7. Use this slide to test the student’s understanding on pointers arithmetic.
  8. Use this slide to test the student’s understanding on one-dimensional arrays and pointers.
  9. Use this slide to test the student’s understanding on 2-D arrays and pointers.
  10. Use this and the next slide to summarize the session.