C Programming : Pointer and Strings
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST11 – Problem Solving and Programming
3/2/2021 4.1 Pointers 2
Syllabus
Contents
1. Pointers
– Memory Access and Pointers
– Pointer basics
– Declaring, Initializing and Dereferencing a pointer
– Parameter Passing Mechanisms
– Operations on Pointers
2. Strings
– String Basics
– Declaring and Initializing a String
– Pointers for String Manipulation
– String handling functions
– Standard and user defined functions
– character oriented functions
– Two dimensional array of strings
3/2/2021 3
4.1 Pointers
Memory Access and Pointers
• A program evaluates a variable by accessing its
memory location and retrieving the value stored
there.
• C permits every legal area of memory to be directly
accessed.
• “legal” because not every memory location is
accessible by our programs.
• The language allows us to obtain the memory location
of every variable, array or structure used in a program.
• We can then use the address of this location to
access—and even change—the value stored there.
• Two values are associated with any variable:
– the address of its memory location and
– the value stored at the location
3/2/2021 4.1 Pointers 4
Pointer Basics
• A pointer is a variable with a difference.
• It contains, not a simple value, but the address of
another variable or object.
• For example,
• if a pointer p is assigned the address of an int
variable x which is set to 5, then
• where
– &x evaluates to the memory address of x.
3/2/2021 4.1 Pointers 5
Pointer Basics
• The pointer p must have been declared
previously as
• C offers two unary operators, the & and *, for
handling pointers.
3/2/2021 4.1 Pointers 6
Pointer Basics
• The & is used to obtain the address of a variable.
• The * is used for two purposes.
• One, to declare the pointer.
– When p is assigned the address of x, p is said to point to x,
which means you can use p to access and change x.
• Second, to obtain the value at the address pointed.
– If p is visible at some location of a program but x is not,
you can still access x at that location by dereferencing p to
obtain the value at the address pointed to, i.e. x.
– The expression *p (second use of *) evaluates to x:
3/2/2021 4.1 Pointers 7
Pointer Basics
• While *p represents the value of x, it can also be used
on the left-hand side of an assignment to change the
value of x:
• The power of a pointer lies in the preceding statement.
The assignment *p = 10 is the same as x = 10.
• A pointer thus provides access to two values—
– the address it stores and
– the value stored at the address
3/2/2021 4.1 Pointers 8
Pointer Basics
• The type of this pointer is not int, but pointer to int,
which we also refer to as int *.
• Even though a pointer has an integer value, it supports
a limited form of arithmetic.
– Adding 1 to a pointer value of 100 yields 101 when the
pointed-to variable is of type char,
– and 104 when the pointed-to variable is of type int.
• Using pointer arithmetic, we can navigate memory
and update the contents at any legal memory location.
• You can change the value stored in the pointer or the
value pointed to:
3/2/2021 4.1 Pointers 9
Pointer Basics
• Like arrays, pointers belong to the category of derived
data types.
• Since every variable has an address,
– we can define pointers for every data type, including
arrays and structures.
– We can also create a pointer to another pointer.
• Arrays and strings can also be treated as pointers for
most purposes.
– The name of an array evaluates to the address of the first
element.
– Double-quoted string evaluates to the address of the first
character of the string.
3/2/2021 4.1 Pointers 10
Pointer Basics
3/2/2021 4.1 Pointers 11
3/2/2021 4.1 Pointers 12
Declaring, Initializing and Dereferencing a pointer
• A pointer variable is declared (and automatically
defined) before use.
• Declaration specifies the type and allocates the
necessary memory for the pointer.
• The following statement declares a pointer variable
named p that can store the address of an int variable.
• By convention, the * is prefixed to the variable, but
you can place it anywhere between int and p
– Int *p
– int * p
– int* p
3/2/2021 4.1 Pointers 13
Declaring, Initializing and Dereferencing a pointer
• The pointer p, which now contains an unpredictable
value, can be used only after it is made to point to a
legal memory location.
• This can be the address of an int variable (say, x), which
is obtained by using the & operator:
• The & operator evaluates its operand (x) as an address.
• We can combine the declaration and assignment in this
manner:
3/2/2021 4.1 Pointers 14
Declaring, Initializing and Dereferencing a pointer
• p has the data type int *, or pointer to int, which simply means that
the value pointed to has the type int.
• Similarly, a float variable is pointed to by a pointer of type float * or
pointer to float.
• However, the size of the pointer itself has no relation to the size of
the variable pointed to.
• A pointer has a fixed size and its value is printed with the %p
format specifier of printf.
• After a pointer has been assigned a valid address with p = &x;
• Use the concept of indirection to obtain the value of x from p.
• The expression *p evaluates to x.
3/2/2021 4.1 Pointers 15
Declaring, Initializing and Dereferencing a pointer
• The *, used as a unary operator in dereferencing or
indirection, operates in the following sequence:
– It evaluates its operand (p) to obtain the stored address
(&x)
– It then fetches the value (x) stored at that address
• Hence, *p is synonymous with x and can be used
wherever x is used.
• Thus, *p changes x when used in the following way:
3/2/2021 4.1 Pointers 16
Declaring, Initializing and Dereferencing a pointer
• As long as p points to x, any change made to x can be
seen by p, and vice versa.
• This is the most important feature of a pointer.
• p thus has two values—
– a direct (&x) and
– an indirect one (*p).
• The dereferenced value of p can also be assigned to
another variable or used in an arithmetic expression:
3/2/2021 4.1 Pointers 17
Declaring, Initializing and Dereferencing a pointer
• The relationship between a pointer and the
variable it points to is depicted in Figure.
3/2/2021 4.1 Pointers 18
3/2/2021 4.1 Pointers 19
Parameter Passing Mechanism
• There are different ways in which parameter data
can be passed into and out of methods and
functions.
• Let us assume that a function B() is called from
another function A().
• In this case A is called the “caller
function” and B is called the “called function or
callee function”.
• Also, the arguments which A sends to B are
called actual arguments and the parameters
of B are called formal arguments.
3/2/2021 4.1 Pointers 20
Parameter Passing Mechanism
• Formal Parameter : A variable and its type as they
appear in the prototype of the function or method.
• Actual Parameter : The variable or expression
corresponding to a formal parameter that appears in
the function or method call in the calling environment.
• Modes:
– IN: Passes info from caller to calle.
– OUT: Callee writes values in caller.
– IN/OUT: Caller tells callee value of variable, which may be
updated by callee.
3/2/2021 4.1 Pointers 21
Pass By Value / Call By Value
• This method uses in-mode semantics.
• Changes made to formal parameter do not get
transmitted back to the caller.
• Any modifications to the formal parameter
variable inside the called function or method
affect only the separate storage location and
will not be reflected in the actual parameter in
the calling environment.
• This method is also called as call by value.
3/2/2021 4.1 Pointers 22
Call By Value
3/2/2021 4.1 Pointers 23
Example
3/2/2021 4.1 Pointers 24
• Shortcomings:
– Inefficiency in storage allocation
– For objects and arrays, the copy semantics are
costly
3/2/2021 4.1 Pointers 25
Pass by reference / Call by reference
• This technique uses in/out-mode semantics.
• Changes made to formal parameter do get
transmitted back to the caller through parameter
passing.
• Any changes to the formal parameter are
reflected in the actual parameter in the calling
environment as formal parameter receives a
reference (or pointer) to the actual data.
• This method is also called as call by reference.
• This method is efficient in both time and space.
3/2/2021 4.1 Pointers 26
Call by reference
3/2/2021 4.1 Pointers 27
Example 1
3/2/2021 4.1 Pointers 28
Example 2
3/2/2021 4.1 Pointers 29
3/2/2021 4.1 Pointers 30
• Shortcomings:
– Many potential scenarios can occur
– Programs are difficult to understand sometimes
3/2/2021 4.1 Pointers 31
Other methods of Parameter Passing
• These techniques are older and were used in earlier programming
languages like Pascal, Algol and Fortran.
• These techniques are not applicable in high level languages.
– Pass by Result : This method uses out-mode semantics. Just before
control is transferred back to the caller, the value of the formal
parameter is transmitted back to the actual parameter. This method is
sometimes called call by result. In general, pass by result technique is
implemented by copy.
– Pass by Value-Result : This method uses in/out-mode semantics. It is a
combination of Pass-by-Value and Pass-by-result. Just before the
control is transferred back to the caller, the value of the formal
parameter is transmitted back to the actual parameter. This method is
sometimes called as call by value-result.
– Pass by name : This technique is used in programming language such
as Algol. In this technique, symbolic “name” of a variable is passed,
which allows it both to be accessed and update.
3/2/2021 4.1 Pointers 32
Operations on Pointers
• Apart from dereferencing with the *, there
are a number of operations that can be
performed on pointers.
• We consider here three types of operations:
– Assignment
– Arithmetic and
– Comparison,
• using a pointer p that points to int.
3/2/2021 4.1 Pointers 33
Assignment
• A pointer can be assigned
– the address of a variable (p = &c;) or
– the name of an array (p = arr;)
• It can also be assigned the value of another
pointer variable of the same type.
3/2/2021 4.1 Pointers 34
Assignment
• It is possible to assign an integer, suitably cast to the
type of the pointer, to a pointer variable using.
• However, you can, and often will, assign the value 0
to a pointer. This value has a synonym in the
symbolic constant, NULL.
• You can assign either 0 or NULL to a pointer of any
type without using a cast
3/2/2021 4.1 Pointers 35
Pointer Arithmetic Using + and -
• The domain of pointer arithmetic is small and simple.
• Among the basic arithmetic operators, only the + and -
can be used with pointers.
• An integer may be added to or subtracted from a
pointer.
• The resultant increase or decrease occurs in terms of
storage units, so p + 2 advances the pointer by two
storage units (12.8.1).
• For an array, this means skipping two elements.
• The following operations on &x and an array element
are also permitted:
3/2/2021 4.1 Pointers 36
Pointer Arithmetic Using + and -
3/2/2021 4.1 Pointers 37
Pointer Arithmetic Using + and -
3/2/2021 4.1 Pointers 38
Pointer Arithmetic Using ++ and --
• A pointer variable can also be used with the
increment and decrement operators.
• Because ++ and -- have the side effect of
changing their operand, they can’t be used
with the name of the array which is a
constant pointer.
• The following expressions are not permitted
for the array arr:
3/2/2021 4.1 Pointers 39
Pointer Arithmetic Using ++ and --
• But if p points to arr, the expressions p++ or --
p are legal.
• p++ increases the pointer to point to the next
array element and p-- decrements it to point
to the previous element.
• If p points to an int variable, each ++ or --
operation changes the numerical value of the
pointer by 4 bytes.
3/2/2021 4.1 Pointers 40
Pointer Arithmetic Using ++ and --
• The expressions p++ and p-- are often
combined with the * for dereferencing the
pointer.
• Expressions like *p++ and ++*p are commonly
used in programs to evaluate the value
pointed to by p, before or after the
incrementing operation.
3/2/2021 4.1 Pointers 41
Example
3/2/2021 4.1 Pointers 42
Comparing Two Pointers
• Finally, two pointers can be compared only if
they point to members of the same array.
• There are two exceptions though.
– First, any pointer can be compared to the null
pointer (p == NULL) that is often returned by a
function when an error condition is encountered.
– Also, a pointer of any type can be compared to a
generic or void pointer
3/2/2021 4.1 Pointers 43
Thank you
3/2/2021 4.1 Pointers 44
C Programming : Pointer and Strings
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST11 – Problem Solving and Programming
3/2/2021 4.2 Strings 46
Syllabus
Contents
1. Pointers
– Memory Access and Pointers
– Pointer basics
– Declaring, Initializing and Dereferencing a pointer
– Parameter Passing Mechanisms
– Operations on Pointers
2. Strings
– String Basics
– Declaring and Initializing a String
– Pointers for String Manipulation
– String handling functions
– Standard and user defined functions
– character oriented functions
– Two dimensional array of strings
3/2/2021 47
4.2 Strings
Strings Basics
• Unlike Java, C doesn’t support a primary data
type for a string.
• The language approaches strings through the
“backdoor”—by tweaking the char data type.
• A string belongs to the category of derived
data types and is interpreted as an array of
type char terminated by the NUL character.
• C offers no keywords or operators for
manipulating strings but its standard library
supports a limited set of string-handling
functions.
3/2/2021 4.2 Strings 48
Strings Basics
• Even though a string is a collection of characters, they are
interpreted differently.
• A character constant is a single-byte integer whose
equivalent symbol is enclosed in single quotes.
– Thus, ‘A’ and its ASCII value, 65, can be used interchangeably in
programs.
• But a string constant is a set of one or more characters
enclosed in double quotes.
– Thus, “A” signifies a string.
– ‘A’ uses one byte but “A” needs two bytes which include the
NUL character.
• Functions that operate on characters don’t work with
strings and vice versa.
3/2/2021 4.2 Strings 49
Strings Basics
• The pointer introduces an additional dimension
to a string.
• The string constant “Micromax” represents a
pointer to the address of its first character.
– i.e., 'M'.
• This string can thus be assigned to a pointer
variable of type char *.
• A string can be manipulated with both array and
pointer notation even though they are not
entirely equivalent.
3/2/2021 4.2 Strings 50
Strings Basics
• Because strings don’t have fixed sizes, every string-
handling function must know where a string begins
and where it ends.
– A function knows the beginning of a string from the
pointer associated with it.
– The end is signified by the NUL character.
• Functions of the standard library that create or modify
strings make sure that the NUL is always in place.
• However, when you create a string-handling function,
it’s your job to append the NUL at the end of the
string.
• NUL has the decimal value 0 and is represented by the
escape sequence ‘0’.
3/2/2021 4.2 Strings 51
Declaring and Initializing a String
• A string can be declared either as
– an array of type char or
– as a pointer of type char *.
• The two techniques of declaration are not
fully equivalent.
• You must understand how they differ and
when to use one technique in preference to
the other.
3/2/2021 4.2 Strings 52
Using an Array to Declare a String
• We have previously declared and initialized an
array with a set of values enclosed in curly
braces.
• The same technique applies to strings as well.
• The following declaration (and definition)
statements also include initialization with a
set of single-quoted characters:
3/2/2021 4.2 Strings 53
Using an Array to Declare a String
• The last element in each case is NUL.
• It has to be explicitly inserted when you
initialize a string like this.
• The first declaration wastes space because
the string uses only nine elements.
• But the compiler automatically sets the size
of stg2 by counting eight items in the list.
3/2/2021 4.2 Strings 54
Using an Array to Declare a String
• Keying in single-quoted characters for initialization is a
tedious job, so C also offers a convenient alternative.
• You can use a double-quoted string to assign an array
at the time of declaration.
• The NUL is automatically inserted when an array is
assigned in this way.
• So, even though sizeof stg1 evaluates to 20 (the
declared size), sizeof stg2 and sizeof stg3 evaluate to 8
and 9 respectively.
3/2/2021 4.2 Strings 55
When an Array is Declared But Not Initialized
3/2/2021 4.2 Strings 56
Using a Pointer to Declare a String
• C supports another way of creating a string.
• Declare a pointer to char.
• Assign a double-quoted string to the pointer
variable.
3/2/2021 4.2 Strings 57
Using a Pointer to Declare a String
• This string comprises multiple words which
– scanf reads with two %s specifiers, but
– printf needs a single %s to print.
• Like with a regular variable, you can combine
declaration and initialization in one
statement.
3/2/2021 4.2 Strings 58
Using a Pointer to Declare a String
• The previous declarations that used an array allocated
memory only for the array.
• But the preceding one creates space in memory for
two objects.
– for the pointer p and
– for the string constant, “Redmi Note”
• It then makes p point to the first character of the
string.
3/2/2021 4.2 Strings 59
3/2/2021 4.2 Strings 60
When an Array of Characters Is Not a String
• An array of characters is not a string when it
doesn’t include the ‘0’ character as the
terminator.
• Usually, we don’t bother to include the NUL
because the compiler does this job for us,
• but negligence on our part can prevent the
compiler from doing so.
3/2/2021 4.2 Strings 61
When an Array of Characters Is Not a String
• Consider the following declarations
• In this scenario, stg5 has no space left to store the NUL character.
• When printf encounters this string, it continues printing beyond
the ‘t’ until it encounters a NUL somewhere on the way.
• This means looking at a region of memory not reserved for it.
• You may see extra characters printed at the end of the word float
or the program could even crash.
• The NUL character has not been explicitly inserted in stg6, so one
would be tempted to conclude that stg6 is not a string.
• However, stg6 is a partially initialized array, which by definition,
has the uninitialized elements set to NUL. Hence, stg6 is a string.
3/2/2021 4.2 Strings 62
3/2/2021 4.2 Strings 63
3/2/2021 4.2 Strings 64
3/2/2021 4.2 Strings 65
Pointers for String Manipulation
• String manipulation is an important
programming activity.
– Navigating a string and
– Accessing each character
• a string can be treated as an array and a pointer.
• By using pointer and array notation in pointer
arithmetic we can manipulate strings.
3/2/2021 4.2 Strings 66
Pointers for String Manipulation
• Consider the following strings defined in two different
ways:
• Because stg is a constant, we can use limited pointer
arithmetic (like stg + 1) to access and update each
element, but we cannot use stg++ and stg--.
• The pointer p, being a variable, knows no such
restrictions. In addition to using expressions like p + 1,
we can also use p++ and p-- to change the current
pointer position in the string.
3/2/2021 4.2 Strings 67
Pointers for String Manipulation
• There is one more difference between stg and p.
• you can change the contents of stg
(“Nyasaland”).
• you can’t change the dereferenced value of p
(“Malawi”) because p is a pointer constant.
• p points to a region of memory that is marked
read-only.
• However, if p is made to point to stg, then you
can change any character in stg using p.
3/2/2021 4.2 Strings 68
Pointers for String Manipulation
3/2/2021 4.2 Strings 69
3/2/2021 4.2 Strings 70
3/2/2021 4.2 Strings 71
String Handling Functions
• There are five string-handling functions can be
perform basically.
– Function to Evaluate Length of a String
– Function to Reverse a String
– Function to Copy a String
– Function to Concatenate Two Strings
– Function to Extract a Substring
3/2/2021 4.2 Strings 72
Function to Evaluate Length of a String
3/2/2021 4.2 Strings 73
Function to Reverse a String
3/2/2021 4.2 Strings 74
Function to Copy a String
3/2/2021 4.2 Strings 75
Function to Concatenate Two Strings
3/2/2021 4.2 Strings 76
3/2/2021 4.2 Strings 77
3/2/2021 4.2 Strings 78
Standard String Handling Functions
3/2/2021 4.2 Strings 79
Scan Set %[...] / %[^...]
• A format specifier of the scanf function that uses
a set of characters enclosed by [ and ]
• Used for matching characters that either belong
or don’t belong to the set.
• The format specifier %[^n] represents a scan set
that matches an entire line not containing the
newline character.
3/2/2021 4.2 Strings 80
Strlen ()
3/2/2021 4.2 Strings 81
Strcpy()
3/2/2021 4.2 Strings 82
Strcat()
3/2/2021 4.2 Strings 83
strcmp()
3/2/2021 4.2 Strings 84
Strchr()
3/2/2021 4.2 Strings 85
Strstr()
3/2/2021 4.2 Strings 86
Character oriented functions
• C supports a number of character-handling functions.
• All character-oriented functions need the #include
<ctype.h> directive.
• Most of these functions test a specific attribute and
simply return true or false.
• For instance, the isdigit function can be used in a loop
to validate a string that must not have any digits.
3/2/2021 4.2 Strings 87
3/2/2021 4.2 Strings 88
3/2/2021 4.2 Strings 89
Two Dimensional Array of Strings
• A string can be stored in an array of type char.
• Multiple strings can be stored in a two-
dimensional array.
• The number of strings that can be stored is
determined by the number of rows (first
subscript).
• the maximum length of each string is set by
the number of columns (second subscript).
3/2/2021 4.2 Strings 90
Two Dimensional Array of Strings
• Here’s how we assign four strings to a 2D array of type
char:
• When using this technique, we need the inner braces
because all four strings are shorter than the number of
columns (12).
• This is not a convenient way of populating arrays with
strings.
3/2/2021 4.2 Strings 91
Two Dimensional Array of Strings
• A simpler method is to use a set of double-
quoted strings enclosed in a single set of
braces:
3/2/2021 4.2 Strings 92
Thank you
3/2/2021 4.2 Strings 93

More Related Content

PDF
C Pointers
PPTX
File in C language
PPTX
File handling in c
PPT
File handling in c
PPTX
Pointers in c++
PPT
Pointers in c
PPTX
Pointers in C Programming
PPTX
Union in C programming
C Pointers
File in C language
File handling in c
File handling in c
Pointers in c++
Pointers in c
Pointers in C Programming
Union in C programming

What's hot (20)

PPT
PPTX
array of object pointer in c++
PPTX
Strings in Java
PPTX
Pointers in c language
PPTX
Strings in C
PPT
Pointers C programming
PPTX
Tokens in C++
PPTX
Pointers in c++
PPTX
PPTX
Pointers,virtual functions and polymorphism cpp
PPT
Structures
PPTX
C programming - String
PPT
Strings in c
PPTX
Inline function
PPTX
Input output statement in C
PPTX
C++ string
PPTX
Virtual base class
PPT
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
PPTX
data types in C programming
PPTX
Pointer in c
array of object pointer in c++
Strings in Java
Pointers in c language
Strings in C
Pointers C programming
Tokens in C++
Pointers in c++
Pointers,virtual functions and polymorphism cpp
Structures
C programming - String
Strings in c
Inline function
Input output statement in C
C++ string
Virtual base class
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
data types in C programming
Pointer in c
Ad

Similar to C Programming : Pointers and Strings (20)

PPTX
C Programming : Pointers and Arrays, Pointers and Strings
PPTX
Chp3(pointers ref)
PPTX
FYBSC(CS)_UNIT-1_Pointers in C.pptx
PPTX
2-Concept of Pointers in c programming.pptx
PPTX
Pointers and Array, pointer and String.pptx
PPTX
Pointer.pptx
PDF
U3_4_PointerArithmetic.pdf people will use the above preaentationa dn
PPT
pointers (1).ppt
PDF
Pointers-Computer programming
PDF
OOP UNIT 1_removed ppt explaining object.pdf
PPT
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
PPT
pointer, structure ,union and intro to file handling
PPT
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
PPT
pointer, structure ,union and intro to file handling
PPT
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
PPT
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
PPTX
ExamRevision_FinalSession_C++ notes.pptx
PPTX
Pointer in C and its significance, Relationship between pointers and memory a...
PDF
PSPC--UNIT-5.pdf
C Programming : Pointers and Arrays, Pointers and Strings
Chp3(pointers ref)
FYBSC(CS)_UNIT-1_Pointers in C.pptx
2-Concept of Pointers in c programming.pptx
Pointers and Array, pointer and String.pptx
Pointer.pptx
U3_4_PointerArithmetic.pdf people will use the above preaentationa dn
pointers (1).ppt
Pointers-Computer programming
OOP UNIT 1_removed ppt explaining object.pdf
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
ExamRevision_FinalSession_C++ notes.pptx
Pointer in C and its significance, Relationship between pointers and memory a...
PSPC--UNIT-5.pdf
Ad

More from Selvaraj Seerangan (20)

PDF
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
PDF
Unit 5 _ Fog Computing .pdf
PDF
CAT III Answer Key.pdf
PPTX
END SEM _ Design Thinking _ 16 Templates.pptx
PPTX
Design Thinking _ Complete Templates.pptx
PPTX
CAT 3 _ List of Templates.pptx
PPTX
[PPT] _ Unit 5 _ Evolve.pptx
PPTX
[PPT] _ Unit 4 _ Engage.pptx
PPTX
[PPT] _ Unit 3 _ Experiment.pptx
PPTX
CAT 2 _ List of Templates.pptx
PPTX
Design Thinking - Empathize Phase
PDF
CAT-II Answer Key.pdf
PDF
PSP LAB MANUAL.pdf
PDF
18CSL51 - Network Lab Manual.pdf
PDF
DS LAB MANUAL.pdf
PPTX
CAT 1 _ List of Templates.pptx
PPTX
[PPT] _ UNIT 1 _ COMPLETE.pptx
DOC
CAT-1 Answer Key.doc
PPTX
Unit 3 Complete.pptx
PDF
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 5 _ Fog Computing .pdf
CAT III Answer Key.pdf
END SEM _ Design Thinking _ 16 Templates.pptx
Design Thinking _ Complete Templates.pptx
CAT 3 _ List of Templates.pptx
[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 3 _ Experiment.pptx
CAT 2 _ List of Templates.pptx
Design Thinking - Empathize Phase
CAT-II Answer Key.pdf
PSP LAB MANUAL.pdf
18CSL51 - Network Lab Manual.pdf
DS LAB MANUAL.pdf
CAT 1 _ List of Templates.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx
CAT-1 Answer Key.doc
Unit 3 Complete.pptx
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf

Recently uploaded (20)

PDF
plant tissues class 6-7 mcqs chatgpt.pdf
PDF
FORM 1 BIOLOGY MIND MAPS and their schemes
PPTX
Module on health assessment of CHN. pptx
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PDF
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
PDF
Race Reva University – Shaping Future Leaders in Artificial Intelligence
PDF
Farming Based Livelihood Systems English Notes
PPTX
Education and Perspectives of Education.pptx
PDF
Literature_Review_methods_ BRACU_MKT426 course material
PPTX
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
PDF
LEARNERS WITH ADDITIONAL NEEDS ProfEd Topic
PDF
English Textual Question & Ans (12th Class).pdf
PDF
Empowerment Technology for Senior High School Guide
PDF
MICROENCAPSULATION_NDDS_BPHARMACY__SEM VII_PCI Syllabus.pdf
PDF
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PPTX
INSTRUMENT AND INSTRUMENTATION PRESENTATION
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PDF
Myanmar Dental Journal, The Journal of the Myanmar Dental Association (2013).pdf
PDF
My India Quiz Book_20210205121199924.pdf
plant tissues class 6-7 mcqs chatgpt.pdf
FORM 1 BIOLOGY MIND MAPS and their schemes
Module on health assessment of CHN. pptx
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
Race Reva University – Shaping Future Leaders in Artificial Intelligence
Farming Based Livelihood Systems English Notes
Education and Perspectives of Education.pptx
Literature_Review_methods_ BRACU_MKT426 course material
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
LEARNERS WITH ADDITIONAL NEEDS ProfEd Topic
English Textual Question & Ans (12th Class).pdf
Empowerment Technology for Senior High School Guide
MICROENCAPSULATION_NDDS_BPHARMACY__SEM VII_PCI Syllabus.pdf
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
INSTRUMENT AND INSTRUMENTATION PRESENTATION
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
Myanmar Dental Journal, The Journal of the Myanmar Dental Association (2013).pdf
My India Quiz Book_20210205121199924.pdf

C Programming : Pointers and Strings

  • 1. C Programming : Pointer and Strings By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
  • 2. 20CST11 – Problem Solving and Programming 3/2/2021 4.1 Pointers 2 Syllabus
  • 3. Contents 1. Pointers – Memory Access and Pointers – Pointer basics – Declaring, Initializing and Dereferencing a pointer – Parameter Passing Mechanisms – Operations on Pointers 2. Strings – String Basics – Declaring and Initializing a String – Pointers for String Manipulation – String handling functions – Standard and user defined functions – character oriented functions – Two dimensional array of strings 3/2/2021 3 4.1 Pointers
  • 4. Memory Access and Pointers • A program evaluates a variable by accessing its memory location and retrieving the value stored there. • C permits every legal area of memory to be directly accessed. • “legal” because not every memory location is accessible by our programs. • The language allows us to obtain the memory location of every variable, array or structure used in a program. • We can then use the address of this location to access—and even change—the value stored there. • Two values are associated with any variable: – the address of its memory location and – the value stored at the location 3/2/2021 4.1 Pointers 4
  • 5. Pointer Basics • A pointer is a variable with a difference. • It contains, not a simple value, but the address of another variable or object. • For example, • if a pointer p is assigned the address of an int variable x which is set to 5, then • where – &x evaluates to the memory address of x. 3/2/2021 4.1 Pointers 5
  • 6. Pointer Basics • The pointer p must have been declared previously as • C offers two unary operators, the & and *, for handling pointers. 3/2/2021 4.1 Pointers 6
  • 7. Pointer Basics • The & is used to obtain the address of a variable. • The * is used for two purposes. • One, to declare the pointer. – When p is assigned the address of x, p is said to point to x, which means you can use p to access and change x. • Second, to obtain the value at the address pointed. – If p is visible at some location of a program but x is not, you can still access x at that location by dereferencing p to obtain the value at the address pointed to, i.e. x. – The expression *p (second use of *) evaluates to x: 3/2/2021 4.1 Pointers 7
  • 8. Pointer Basics • While *p represents the value of x, it can also be used on the left-hand side of an assignment to change the value of x: • The power of a pointer lies in the preceding statement. The assignment *p = 10 is the same as x = 10. • A pointer thus provides access to two values— – the address it stores and – the value stored at the address 3/2/2021 4.1 Pointers 8
  • 9. Pointer Basics • The type of this pointer is not int, but pointer to int, which we also refer to as int *. • Even though a pointer has an integer value, it supports a limited form of arithmetic. – Adding 1 to a pointer value of 100 yields 101 when the pointed-to variable is of type char, – and 104 when the pointed-to variable is of type int. • Using pointer arithmetic, we can navigate memory and update the contents at any legal memory location. • You can change the value stored in the pointer or the value pointed to: 3/2/2021 4.1 Pointers 9
  • 10. Pointer Basics • Like arrays, pointers belong to the category of derived data types. • Since every variable has an address, – we can define pointers for every data type, including arrays and structures. – We can also create a pointer to another pointer. • Arrays and strings can also be treated as pointers for most purposes. – The name of an array evaluates to the address of the first element. – Double-quoted string evaluates to the address of the first character of the string. 3/2/2021 4.1 Pointers 10
  • 13. Declaring, Initializing and Dereferencing a pointer • A pointer variable is declared (and automatically defined) before use. • Declaration specifies the type and allocates the necessary memory for the pointer. • The following statement declares a pointer variable named p that can store the address of an int variable. • By convention, the * is prefixed to the variable, but you can place it anywhere between int and p – Int *p – int * p – int* p 3/2/2021 4.1 Pointers 13
  • 14. Declaring, Initializing and Dereferencing a pointer • The pointer p, which now contains an unpredictable value, can be used only after it is made to point to a legal memory location. • This can be the address of an int variable (say, x), which is obtained by using the & operator: • The & operator evaluates its operand (x) as an address. • We can combine the declaration and assignment in this manner: 3/2/2021 4.1 Pointers 14
  • 15. Declaring, Initializing and Dereferencing a pointer • p has the data type int *, or pointer to int, which simply means that the value pointed to has the type int. • Similarly, a float variable is pointed to by a pointer of type float * or pointer to float. • However, the size of the pointer itself has no relation to the size of the variable pointed to. • A pointer has a fixed size and its value is printed with the %p format specifier of printf. • After a pointer has been assigned a valid address with p = &x; • Use the concept of indirection to obtain the value of x from p. • The expression *p evaluates to x. 3/2/2021 4.1 Pointers 15
  • 16. Declaring, Initializing and Dereferencing a pointer • The *, used as a unary operator in dereferencing or indirection, operates in the following sequence: – It evaluates its operand (p) to obtain the stored address (&x) – It then fetches the value (x) stored at that address • Hence, *p is synonymous with x and can be used wherever x is used. • Thus, *p changes x when used in the following way: 3/2/2021 4.1 Pointers 16
  • 17. Declaring, Initializing and Dereferencing a pointer • As long as p points to x, any change made to x can be seen by p, and vice versa. • This is the most important feature of a pointer. • p thus has two values— – a direct (&x) and – an indirect one (*p). • The dereferenced value of p can also be assigned to another variable or used in an arithmetic expression: 3/2/2021 4.1 Pointers 17
  • 18. Declaring, Initializing and Dereferencing a pointer • The relationship between a pointer and the variable it points to is depicted in Figure. 3/2/2021 4.1 Pointers 18
  • 20. Parameter Passing Mechanism • There are different ways in which parameter data can be passed into and out of methods and functions. • Let us assume that a function B() is called from another function A(). • In this case A is called the “caller function” and B is called the “called function or callee function”. • Also, the arguments which A sends to B are called actual arguments and the parameters of B are called formal arguments. 3/2/2021 4.1 Pointers 20
  • 21. Parameter Passing Mechanism • Formal Parameter : A variable and its type as they appear in the prototype of the function or method. • Actual Parameter : The variable or expression corresponding to a formal parameter that appears in the function or method call in the calling environment. • Modes: – IN: Passes info from caller to calle. – OUT: Callee writes values in caller. – IN/OUT: Caller tells callee value of variable, which may be updated by callee. 3/2/2021 4.1 Pointers 21
  • 22. Pass By Value / Call By Value • This method uses in-mode semantics. • Changes made to formal parameter do not get transmitted back to the caller. • Any modifications to the formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. • This method is also called as call by value. 3/2/2021 4.1 Pointers 22
  • 23. Call By Value 3/2/2021 4.1 Pointers 23
  • 25. • Shortcomings: – Inefficiency in storage allocation – For objects and arrays, the copy semantics are costly 3/2/2021 4.1 Pointers 25
  • 26. Pass by reference / Call by reference • This technique uses in/out-mode semantics. • Changes made to formal parameter do get transmitted back to the caller through parameter passing. • Any changes to the formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference (or pointer) to the actual data. • This method is also called as call by reference. • This method is efficient in both time and space. 3/2/2021 4.1 Pointers 26
  • 27. Call by reference 3/2/2021 4.1 Pointers 27
  • 28. Example 1 3/2/2021 4.1 Pointers 28
  • 29. Example 2 3/2/2021 4.1 Pointers 29
  • 31. • Shortcomings: – Many potential scenarios can occur – Programs are difficult to understand sometimes 3/2/2021 4.1 Pointers 31
  • 32. Other methods of Parameter Passing • These techniques are older and were used in earlier programming languages like Pascal, Algol and Fortran. • These techniques are not applicable in high level languages. – Pass by Result : This method uses out-mode semantics. Just before control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter. This method is sometimes called call by result. In general, pass by result technique is implemented by copy. – Pass by Value-Result : This method uses in/out-mode semantics. It is a combination of Pass-by-Value and Pass-by-result. Just before the control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter. This method is sometimes called as call by value-result. – Pass by name : This technique is used in programming language such as Algol. In this technique, symbolic “name” of a variable is passed, which allows it both to be accessed and update. 3/2/2021 4.1 Pointers 32
  • 33. Operations on Pointers • Apart from dereferencing with the *, there are a number of operations that can be performed on pointers. • We consider here three types of operations: – Assignment – Arithmetic and – Comparison, • using a pointer p that points to int. 3/2/2021 4.1 Pointers 33
  • 34. Assignment • A pointer can be assigned – the address of a variable (p = &c;) or – the name of an array (p = arr;) • It can also be assigned the value of another pointer variable of the same type. 3/2/2021 4.1 Pointers 34
  • 35. Assignment • It is possible to assign an integer, suitably cast to the type of the pointer, to a pointer variable using. • However, you can, and often will, assign the value 0 to a pointer. This value has a synonym in the symbolic constant, NULL. • You can assign either 0 or NULL to a pointer of any type without using a cast 3/2/2021 4.1 Pointers 35
  • 36. Pointer Arithmetic Using + and - • The domain of pointer arithmetic is small and simple. • Among the basic arithmetic operators, only the + and - can be used with pointers. • An integer may be added to or subtracted from a pointer. • The resultant increase or decrease occurs in terms of storage units, so p + 2 advances the pointer by two storage units (12.8.1). • For an array, this means skipping two elements. • The following operations on &x and an array element are also permitted: 3/2/2021 4.1 Pointers 36
  • 37. Pointer Arithmetic Using + and - 3/2/2021 4.1 Pointers 37
  • 38. Pointer Arithmetic Using + and - 3/2/2021 4.1 Pointers 38
  • 39. Pointer Arithmetic Using ++ and -- • A pointer variable can also be used with the increment and decrement operators. • Because ++ and -- have the side effect of changing their operand, they can’t be used with the name of the array which is a constant pointer. • The following expressions are not permitted for the array arr: 3/2/2021 4.1 Pointers 39
  • 40. Pointer Arithmetic Using ++ and -- • But if p points to arr, the expressions p++ or -- p are legal. • p++ increases the pointer to point to the next array element and p-- decrements it to point to the previous element. • If p points to an int variable, each ++ or -- operation changes the numerical value of the pointer by 4 bytes. 3/2/2021 4.1 Pointers 40
  • 41. Pointer Arithmetic Using ++ and -- • The expressions p++ and p-- are often combined with the * for dereferencing the pointer. • Expressions like *p++ and ++*p are commonly used in programs to evaluate the value pointed to by p, before or after the incrementing operation. 3/2/2021 4.1 Pointers 41
  • 43. Comparing Two Pointers • Finally, two pointers can be compared only if they point to members of the same array. • There are two exceptions though. – First, any pointer can be compared to the null pointer (p == NULL) that is often returned by a function when an error condition is encountered. – Also, a pointer of any type can be compared to a generic or void pointer 3/2/2021 4.1 Pointers 43
  • 44. Thank you 3/2/2021 4.1 Pointers 44
  • 45. C Programming : Pointer and Strings By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
  • 46. 20CST11 – Problem Solving and Programming 3/2/2021 4.2 Strings 46 Syllabus
  • 47. Contents 1. Pointers – Memory Access and Pointers – Pointer basics – Declaring, Initializing and Dereferencing a pointer – Parameter Passing Mechanisms – Operations on Pointers 2. Strings – String Basics – Declaring and Initializing a String – Pointers for String Manipulation – String handling functions – Standard and user defined functions – character oriented functions – Two dimensional array of strings 3/2/2021 47 4.2 Strings
  • 48. Strings Basics • Unlike Java, C doesn’t support a primary data type for a string. • The language approaches strings through the “backdoor”—by tweaking the char data type. • A string belongs to the category of derived data types and is interpreted as an array of type char terminated by the NUL character. • C offers no keywords or operators for manipulating strings but its standard library supports a limited set of string-handling functions. 3/2/2021 4.2 Strings 48
  • 49. Strings Basics • Even though a string is a collection of characters, they are interpreted differently. • A character constant is a single-byte integer whose equivalent symbol is enclosed in single quotes. – Thus, ‘A’ and its ASCII value, 65, can be used interchangeably in programs. • But a string constant is a set of one or more characters enclosed in double quotes. – Thus, “A” signifies a string. – ‘A’ uses one byte but “A” needs two bytes which include the NUL character. • Functions that operate on characters don’t work with strings and vice versa. 3/2/2021 4.2 Strings 49
  • 50. Strings Basics • The pointer introduces an additional dimension to a string. • The string constant “Micromax” represents a pointer to the address of its first character. – i.e., 'M'. • This string can thus be assigned to a pointer variable of type char *. • A string can be manipulated with both array and pointer notation even though they are not entirely equivalent. 3/2/2021 4.2 Strings 50
  • 51. Strings Basics • Because strings don’t have fixed sizes, every string- handling function must know where a string begins and where it ends. – A function knows the beginning of a string from the pointer associated with it. – The end is signified by the NUL character. • Functions of the standard library that create or modify strings make sure that the NUL is always in place. • However, when you create a string-handling function, it’s your job to append the NUL at the end of the string. • NUL has the decimal value 0 and is represented by the escape sequence ‘0’. 3/2/2021 4.2 Strings 51
  • 52. Declaring and Initializing a String • A string can be declared either as – an array of type char or – as a pointer of type char *. • The two techniques of declaration are not fully equivalent. • You must understand how they differ and when to use one technique in preference to the other. 3/2/2021 4.2 Strings 52
  • 53. Using an Array to Declare a String • We have previously declared and initialized an array with a set of values enclosed in curly braces. • The same technique applies to strings as well. • The following declaration (and definition) statements also include initialization with a set of single-quoted characters: 3/2/2021 4.2 Strings 53
  • 54. Using an Array to Declare a String • The last element in each case is NUL. • It has to be explicitly inserted when you initialize a string like this. • The first declaration wastes space because the string uses only nine elements. • But the compiler automatically sets the size of stg2 by counting eight items in the list. 3/2/2021 4.2 Strings 54
  • 55. Using an Array to Declare a String • Keying in single-quoted characters for initialization is a tedious job, so C also offers a convenient alternative. • You can use a double-quoted string to assign an array at the time of declaration. • The NUL is automatically inserted when an array is assigned in this way. • So, even though sizeof stg1 evaluates to 20 (the declared size), sizeof stg2 and sizeof stg3 evaluate to 8 and 9 respectively. 3/2/2021 4.2 Strings 55
  • 56. When an Array is Declared But Not Initialized 3/2/2021 4.2 Strings 56
  • 57. Using a Pointer to Declare a String • C supports another way of creating a string. • Declare a pointer to char. • Assign a double-quoted string to the pointer variable. 3/2/2021 4.2 Strings 57
  • 58. Using a Pointer to Declare a String • This string comprises multiple words which – scanf reads with two %s specifiers, but – printf needs a single %s to print. • Like with a regular variable, you can combine declaration and initialization in one statement. 3/2/2021 4.2 Strings 58
  • 59. Using a Pointer to Declare a String • The previous declarations that used an array allocated memory only for the array. • But the preceding one creates space in memory for two objects. – for the pointer p and – for the string constant, “Redmi Note” • It then makes p point to the first character of the string. 3/2/2021 4.2 Strings 59
  • 61. When an Array of Characters Is Not a String • An array of characters is not a string when it doesn’t include the ‘0’ character as the terminator. • Usually, we don’t bother to include the NUL because the compiler does this job for us, • but negligence on our part can prevent the compiler from doing so. 3/2/2021 4.2 Strings 61
  • 62. When an Array of Characters Is Not a String • Consider the following declarations • In this scenario, stg5 has no space left to store the NUL character. • When printf encounters this string, it continues printing beyond the ‘t’ until it encounters a NUL somewhere on the way. • This means looking at a region of memory not reserved for it. • You may see extra characters printed at the end of the word float or the program could even crash. • The NUL character has not been explicitly inserted in stg6, so one would be tempted to conclude that stg6 is not a string. • However, stg6 is a partially initialized array, which by definition, has the uninitialized elements set to NUL. Hence, stg6 is a string. 3/2/2021 4.2 Strings 62
  • 66. Pointers for String Manipulation • String manipulation is an important programming activity. – Navigating a string and – Accessing each character • a string can be treated as an array and a pointer. • By using pointer and array notation in pointer arithmetic we can manipulate strings. 3/2/2021 4.2 Strings 66
  • 67. Pointers for String Manipulation • Consider the following strings defined in two different ways: • Because stg is a constant, we can use limited pointer arithmetic (like stg + 1) to access and update each element, but we cannot use stg++ and stg--. • The pointer p, being a variable, knows no such restrictions. In addition to using expressions like p + 1, we can also use p++ and p-- to change the current pointer position in the string. 3/2/2021 4.2 Strings 67
  • 68. Pointers for String Manipulation • There is one more difference between stg and p. • you can change the contents of stg (“Nyasaland”). • you can’t change the dereferenced value of p (“Malawi”) because p is a pointer constant. • p points to a region of memory that is marked read-only. • However, if p is made to point to stg, then you can change any character in stg using p. 3/2/2021 4.2 Strings 68
  • 69. Pointers for String Manipulation 3/2/2021 4.2 Strings 69
  • 72. String Handling Functions • There are five string-handling functions can be perform basically. – Function to Evaluate Length of a String – Function to Reverse a String – Function to Copy a String – Function to Concatenate Two Strings – Function to Extract a Substring 3/2/2021 4.2 Strings 72
  • 73. Function to Evaluate Length of a String 3/2/2021 4.2 Strings 73
  • 74. Function to Reverse a String 3/2/2021 4.2 Strings 74
  • 75. Function to Copy a String 3/2/2021 4.2 Strings 75
  • 76. Function to Concatenate Two Strings 3/2/2021 4.2 Strings 76
  • 79. Standard String Handling Functions 3/2/2021 4.2 Strings 79
  • 80. Scan Set %[...] / %[^...] • A format specifier of the scanf function that uses a set of characters enclosed by [ and ] • Used for matching characters that either belong or don’t belong to the set. • The format specifier %[^n] represents a scan set that matches an entire line not containing the newline character. 3/2/2021 4.2 Strings 80
  • 87. Character oriented functions • C supports a number of character-handling functions. • All character-oriented functions need the #include <ctype.h> directive. • Most of these functions test a specific attribute and simply return true or false. • For instance, the isdigit function can be used in a loop to validate a string that must not have any digits. 3/2/2021 4.2 Strings 87
  • 90. Two Dimensional Array of Strings • A string can be stored in an array of type char. • Multiple strings can be stored in a two- dimensional array. • The number of strings that can be stored is determined by the number of rows (first subscript). • the maximum length of each string is set by the number of columns (second subscript). 3/2/2021 4.2 Strings 90
  • 91. Two Dimensional Array of Strings • Here’s how we assign four strings to a 2D array of type char: • When using this technique, we need the inner braces because all four strings are shorter than the number of columns (12). • This is not a convenient way of populating arrays with strings. 3/2/2021 4.2 Strings 91
  • 92. Two Dimensional Array of Strings • A simpler method is to use a set of double- quoted strings enclosed in a single set of braces: 3/2/2021 4.2 Strings 92