SlideShare a Scribd company logo
1 of 156
UNIT I : Pointers and Arrays, Pointers
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.
20CST21 – Programming and Linear Data Structures
Preamble and Course Outcomes
4/21/2021 1.0 _ Pointers and Arrays 2
Syllabus – Unit Wise
4/21/2021 1.0 _ Pointers and Arrays 3
List of Exercises
4/21/2021 1.0 _ Pointers and Arrays 4
Text Book and Reference Book
4/21/2021 1.0 _ Pointers and Arrays 5
Unit I : Contents
1. Pointers- Introduction
2. Pointers and 1D array
3. Passing an array to a function
4. Returning an array from function
5. NULL pointers
6. Array of pointers
7. Pointer-to-pointer
8. Pointers and 2D array
9. Generic pointers
10. Dangling Pointer
11. Using Pointers for string manipulation
12. Two dimensional array of strings
13. Array of pointers to strings.
4/21/2021 6
1.0 _ Pointers and Arrays
Pointers- Introduction
• Every variable in C language has a name and a
value associated with it.
• When a variable is declared, a specific block
of memory within the computer is allocated
to hold the value of that variable.
• Each memory location has a distinct address.
4/21/2021 1.0 _ Pointers and Arrays 7
Pointers- Introduction
• For example,
– we live in a house and our house has an address,
which helps other people to identify our house.
• The same way the value of the variable is
identified using the address of that variable.
• This address of the variable or memory location
can be stored in a pointer.
4/21/2021 1.0 _ Pointers and Arrays 8
Pointers- Introduction
• Using pointer we can have direct access to a
memory location because they store address
of a variable or memory location.
• Pointers are closely related to low level
memory operations.
• Before introducing the pointers in
programming, let us understand what
happens during a variable definition.
4/21/2021 1.0 _ Pointers and Arrays 9
Pointers- Introduction
• Let us consider the following statement :
• When the above statement is compiled and
executed, the following will happen:
– The compiler allocates memory to store an integer.
– Next , compiler assigns a label to the allocated
memory location as n.
– Finally, the constant 10 is stored in that location.
4/21/2021 1.0 _ Pointers and Arrays 10
Advantages of Pointers
• Pointers provide direct access to memory.
• Pointers are used to return more than one value from
a function.
• Pointers allow dynamic memory allocation and
deallocation.
• Reduces the storage space required by the program.
• Pointers are more efficient in handling arrays and
structures.
• Pointers are used to get reference of a variable or
function.
• Pointers increases program execution speed.
• Pointer allows to create complex data structures such
as linked list, stack, queues, trees, graphs etc.
4/21/2021 1.0 _ Pointers and Arrays 11
Pointers- Introduction
• Pointer is a variable which stores the address
of another variable.
• It is used to allocate memory dynamically.
• Memory allocation done at run time is known
as Dynamic memory allocation.
• Pointer variable may be any valid C data type
such as int, float, double, char etc.
• For any type of pointers, only four bytes of
memory is allocated for storing the address.
4/21/2021 1.0 _ Pointers and Arrays 12
Example
4/21/2021 1.0 _ Pointers and Arrays 13
Pointer Declaration
4/21/2021 1.0 _ Pointers and Arrays 14
• Pointer can be declared with a variable preceded by *.
• Pointer can be declared using the following syntax:
Pointer operators
• Reference or Address of operator (&)
• Dereference operator or indirection operator
or Value at Address Operator (*)
4/21/2021 1.0 _ Pointers and Arrays 15
Reference Operator - Example
4/21/2021 1.0 _ Pointers and Arrays 16
Dereference operator (*)
• To access the value at the address stored in the
pointer variable, we can use dereference
operator (*).
• This is an unary operator * that returns the value
of the variable located at the address specified by
its operand.
4/21/2021 1.0 _ Pointers and Arrays 17
Dereference Operator - Example
4/21/2021 1.0 _ Pointers and Arrays 18
Example 1
4/21/2021 1.0 _ Pointers and Arrays 19
4/21/2021 1.0 _ Pointers and Arrays 20
Swapping using function and pointers
• we have to use pointers concept.
• Bz,
– Parameters are always passed by value in C and
– function can not return more than one value.
4/21/2021 1.0 _ Pointers and Arrays 21
Example 2
4/21/2021 1.0 _ Pointers and Arrays 22
Example 3
4/21/2021 1.0 _ Pointers and Arrays 23
Pointer Arithmetic
• A pointer is a variable which holds the address of another
variable.
• Address is represented by a numeric value.
• We cannot perform every type of arithmetic operation on
pointers.
• The following arithmetic operations are the only valid
arithmetic operations performed on pointers:
4/21/2021 1.0 _ Pointers and Arrays 24
Pointer Arithmetic
• For example, assume the integer pointer ptr
which contains the address 1000.
• If we are incrementing the pointer ptr by 1 (using
++ptr or ptr++), we will get 1002 (i.e 1000 + 1 * 2)
• Instead of 1001 because the size of the int data
type is 2 bytes (Note: Size of the datatype
changes depends on the compiler used).
• If we are using a system where the size of int is 4
bytes then we would get 1004 ( i.e 1000 + 1 * 4 ).
4/21/2021 1.0 _ Pointers and Arrays 25
Pointer Arithmetic - Example
• Suppose the address of the variables i, f and ch are
1000, 2000 , 3000 respectively. Therefore iptr, fptr and
cptr will have initial values of 1000, 2000 and 3000.
Assume 1, 2 and 4 bytes of memory is allocated for
char, int and float variables respectively.
4/21/2021 1.0 _ Pointers and Arrays 26
4/21/2021 1.0 _ Pointers and Arrays 27
4/21/2021 1.0 _ Pointers and Arrays 28
4/21/2021 1.0 _ Pointers and Arrays 29
Example 4 - Print all the alphabets using pointer
4/21/2021 1.0 _ Pointers and Arrays 30
Example 5 - Add two integers using pointers
4/21/2021 1.0 _ Pointers and Arrays 31
Example 6 - Add two integers using function by
passing address of two numbers as arguments
to function.
4/21/2021 1.0 _ Pointers and Arrays 32
Pointer Arithmetic between Two Pointers
• Arithmetic operation between two pointers is
performed only on same type of pointers.
• Let us take two integer pointers ptr1 and ptr2
with addresses 1000 and 1008 respectively.
• The expression ptr2 - ptr1 will give the result
as 4, since the memory location allocated for
integer data type is 2 bytes.
• If we subtract ptr2 from ptr1 i.e the
expression (ptr1 - ptr2) will give the result -4.
4/21/2021 1.0 _ Pointers and Arrays 33
Example 7
4/21/2021 1.0 _ Pointers and Arrays 34
Thank you
4/21/2021 1.0 _ Pointers and Arrays 35
UNIT I : Pointers and Arrays, Pointers
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.
20CST21 – Programming and Linear Data Structures
Unit I : Contents
1. Pointers- Introduction
2. Pointers and 1D array
3. Passing an array to a function
4. Returning an array from function
5. NULL pointers
6. Array of pointers
7. Pointer-to-pointer
8. Pointers and 2D array
9. Generic pointers
10. Dangling Pointer
11. Using Pointers for string manipulation
12. Two dimensional array of strings
13. Array of pointers to strings.
4/21/2021 37
2.0 _ Pointers and Arrays
Pointers and Arrays
• We are already familiar with arrays, which store multiple values of
the same data type.
• Array elements are stored in contiguous memory locations.
• When an array is declared, compiler allocates required amount of
contiguous memory locations to hold all the elements of the array.
• Memory is allocated by the compiler during compilation time itself.
• Base address of the array is the address of the first element of the
array.
• We can create a pointer which can be used to point an array.
• In an one dimensional array, we can use single subscript to access
the array elements.
• Name of the 1-D array or &array[0] points to the address of the
first element of an array.
4/21/2021 2.0 _ Pointers and Arrays 38
Pointers and 1D Arrays
• Suppose we declare an integer array “A” with 5
elements and assuming that the base address of the
array a is 1000 and each integer element requires two
bytes of memory.
• The five elements will be stored as follows:
• Here array name “A” acts as a constant pointer which
will give the base address of the array and points to
the first element of the array, A[0].
– i.e., the value of A and &A[0] are same.
4/21/2021 2.0 _ Pointers and Arrays 39
Pointers and 1D Arrays
• We can declare another pointer of type int to point to the
array A.
• Now we can access every element of the array A using
pointer p.
• (*p) is used to access the element A[0] which has the value
1 in the given example.
• To access the next element in the array A,
– increment the pointer p by 1 using (p++) or (++p).
– Now we can give *p to get A[1].
– It gives the value 2.
– To get the next element in the array A, increment the pointer p
by 1 and use *p.
4/21/2021 2.0 _ Pointers and Arrays 40
Example 1- Program to demonstrates the use of
pointer to access the array elements
4/21/2021 2.0 _ Pointers and Arrays 41
Example 2- use array name as a pointer to
access the array elements
4/21/2021 2.0 _ Pointers and Arrays 42
• In the above program, A is a constant pointer which always
points to first element A[0].
• We cannot move this pointer to next element using ++
operator since base address of the array cannot be
changed.
• To access the elements of the array using a constant
pointer A, we can use the following statements:
4/21/2021 2.0 _ Pointers and Arrays 43
Example 3- Program to display the elements of
an array in reverse order using pointer.
4/21/2021 2.0 _ Pointers and Arrays 44
Example 4 – Program to add the elements of an
array using pointer
4/21/2021 2.0 _ Pointers and Arrays 45
Example 5 – Program to demonstrate increment and
decrement operators with pointers and arrays.
4/21/2021 2.0 _ Pointers and Arrays 46
Example 6 - Program to copy an array to another array
using pointers
4/21/2021 2.0 _ Pointers and Arrays 47
Thank you
4/21/2021 2.0 _ Pointers and Arrays 48
UNIT I : Pointers and Arrays, Pointers
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.
20CST21 – Programming and Linear Data Structures
Unit I : Contents
1. Pointers- Introduction
2. Pointers and 1D array
3. Passing an array to a function
4. Returning an array from function
5. Pointers and 2D array
6. NULL pointers
7. Array of pointers
8. Pointer-to-pointer
9. Generic pointers
10. Dangling Pointer
11. Using Pointers for string manipulation
12. Two dimensional array of strings
13. Array of pointers to strings.
4/21/2021 50
2.0 _ Passing and Returing an array
to_from a function
Passing an array to a function
• We can pass an individual elements or entire
array to a function as an argument.
• To pass an entire array to a function, only the
name of the array is passed as an argument.
• When address is passed as an argument, the
function definition should have an array or a
pointer as a parameter to receive the passed
address.
• When an array is passed to a function, the
changes made by the function affect the original
array.
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
51
Function Definition with array as a
parameter
• We can receive an array in a function using one of
the following two methods.
• The name of the array is passes as an argument,
which is the address of the first element of the
array.
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
52
Example 1 – Program to demonstrate the
average of all the elements of an array.
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
53
Method 1
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
54
Method 2
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
55
Method 3
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
56
Example 2 - Write a program in C to
sort an array using Pointer
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
57
Returning an array from a function
• C does not allow to return an entire array
from a function.
• However, we can return a pointer to the base
address(address of first element of array) of
an array by specifying the name of the array
without an index.
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
58
Returning an array from a function
• If we want to return a 1-D array from a
function, we have to declare a function
returning a pointer as in the following
example :
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
59
Returning an array from a function
• We should not return base pointer of a local
array declared inside a function because as
soon as control returns from a function all
local variables gets destroyed.
• If we want to return a local array then we
should declare it as a static variable so that it
retains it's value after function call.
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
60
Example 2 - Program to generate first N
even numbers and return as an array.
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
61
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
62
Thank you
4/21/2021
2.0 _ Passing and Returing an array
to_from a function
63
UNIT I : Pointers and Arrays, Pointers
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.
20CST21 – Programming and Linear Data Structures
Unit I : Contents
1. Pointers- Introduction
2. Pointers and 1D array
3. Passing an array to a function
4. Returning an array from function
5. Pointers and 2D array
6. Array of pointers
7. NULL pointers
8. Pointer-to-pointer
9. Generic pointers
10. Dangling Pointer
11. Using Pointers for string manipulation
12. Two dimensional array of strings
13. Array of pointers to strings.
4/21/2021 65
1.4 _ Pointers and 2D Arrays
Pointers and 2D array
• In a two dimensional array, we can access
each element by using two subscripts.
– first subscript represents the row number and
– second subscript represents the column number
• Consider the following declaration statement,
4/21/2021 1.4 _ Pointers and 2D Arrays 66
Pointers and 2D array
• The above declaration statement creates a
3x4 matrix initialized with the following
values:
4/21/2021 1.4 _ Pointers and 2D Arrays 67
Pointers and 2D array
• The element at ith row, jth column can be accessed
using a[i][j].
• To access the value 7, we have to use a[1][2].
• Let us see how pointer is used to access the 2-D array.
• As we know, name of the array gives the base address
of the array i.e., address of a[0][0].
• To access a[i][j] using base pointer of the array, we can
use the following generalized form:
4/21/2021 1.4 _ Pointers and 2D Arrays 68
Pointers and 2D array
• The following figure shows how the above 2-D array
will be stored in memory.
• Array elements are stored in memory row by row.
4/21/2021 1.4 _ Pointers and 2D Arrays 69
Pointers and 2D array
• In a 2-D array, each row will be considered as a one
dimensional array.
• Hence 2-D array can be considered as a collection of
several one dimensional arrays.
• In this example, each row is an array of 4 integers.
• We know that the name of an array is a constant pointer
that points to 0th row which contains address 1000.
4/21/2021 1.4 _ Pointers and 2D Arrays 70
Pointers and 2D array
4/21/2021 1.4 _ Pointers and 2D Arrays 71
Pointers and 2D array
• Consider a two dimensional array mat[ROWS] [COLS]
where ROWS and COLS are some integer value.
• We can use any one of the following two notations to
access the two dimensional array.
• The first int mat[][COLS] is general array notation.
• Whereas int (*mat)[COLS] is a pointer to array.
4/21/2021 1.4 _ Pointers and 2D Arrays 72
Example - read and display a 3x3 matrix
4/21/2021 1.4 _ Pointers and 2D Arrays 73
Passing a 2D array to a function
• For passing multidimensional arrays,
– First array dimension does not have to be
specified.
– The second dimension must be explicitly
specified or a pointer to pointer as a parameter
to receive the address.
4/21/2021 1.4 _ Pointers and 2D Arrays 74
Example - print 2-D array using function
4/21/2021 1.4 _ Pointers and 2D Arrays 75
Example - add two 3 x 3 matrices using pointer
4/21/2021 1.4 _ Pointers and 2D Arrays 76
4/21/2021 1.4 _ Pointers and 2D Arrays 77
4/21/2021 1.4 _ Pointers and 2D Arrays 78
4/21/2021 1.4 _ Pointers and 2D Arrays 79
4/21/2021 1.4 _ Pointers and 2D Arrays 80
Example - display Lower triangular and Upper
triangular of a given matrix of size mxn
4/21/2021 1.4 _ Pointers and 2D Arrays 81
4/21/2021 1.4 _ Pointers and 2D Arrays 82
4/21/2021 1.4 _ Pointers and 2D Arrays 83
4/21/2021 1.4 _ Pointers and 2D Arrays 84
4/21/2021 1.4 _ Pointers and 2D Arrays 85
Example - to print and find sum of diagonal
elements of a given matrix.
4/21/2021 1.4 _ Pointers and 2D Arrays 86
4/21/2021 1.4 _ Pointers and 2D Arrays 87
4/21/2021 1.4 _ Pointers and 2D Arrays 88
4/21/2021 1.4 _ Pointers and 2D Arrays 89
4/21/2021 1.4 _ Pointers and 2D Arrays 90
Returning a 2D array from Function
• Returning a 2D array from function is not as straight as
passing an array to a function.
• Arrays in C are passed by reference, hence any changes
made to array passed as argument persists after the
function.
• So you can accept the output array you need to return, as a
parameter to the function.
• The following program demonstrates how a 2-D array is
returned from a function by passing resultant array also as
a parameter.
• In the following program, main() receives two matrices as
input and these two matrices along with resultant matrix
are passed as arguments to the function sum().
• The sum() function adds the two matrices and return the
resultant matrix as result to the main() function.
4/21/2021 1.4 _ Pointers and 2D Arrays 91
4/21/2021 1.4 _ Pointers and 2D Arrays 92
4/21/2021 1.4 _ Pointers and 2D Arrays 93
4/21/2021 1.4 _ Pointers and 2D Arrays 94
4/21/2021 1.4 _ Pointers and 2D Arrays 95
4/21/2021 1.4 _ Pointers and 2D Arrays 96
Further Reference
To
Pass and Return an array(1D & 2D) to / from function
with/without using pointers
please refer
this
link......
• https://codeforwin.org/2017/12/pass-return-
array-function-c.html#return-array-multi
4/21/2021 1.4 _ Pointers and 2D Arrays 97
Thank you
4/21/2021 1.4 _ Pointers and 2D Arrays 98
UNIT I : Pointers and Arrays, Pointers
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.
20CST21 – Programming and Linear Data Structures
Unit I : Contents
1. Pointers- Introduction
2. Pointers and 1D array
3. Passing an array to a function
4. Returning an array from function
5. Pointers and 2D array
6. Array of pointers
7. NULL pointers
8. Pointer-to-pointer
9. Generic pointers
10. Dangling Pointer
11. Using Pointers for string manipulation
12. Two dimensional array of strings
13. Array of pointers to strings.
4/21/2021 100
1.5 _ Pointers Concepts
Array of Pointers
• When we want to maintain an array to store the
address of memory locations of type int or float
or char or any other data type available, we have
to create an array of pointers.
• Here is the syntax to declare an array of pointers
which is almost same as that of declaring an
array of int, float or char etc.,
4/21/2021 1.5 _ Pointers Concepts 101
Array of Pointers
• Here ptr is an array of 5 integer pointers ie., the
integer pointers are ptr[0], ptr[1] ….ptr[4].
• Each element in this array can hold the address of
an integer variable.
4/21/2021 1.5 _ Pointers Concepts 102
Example
4/21/2021 1.5 _ Pointers Concepts 103
NULL Pointer
• Pointer is assigned a value NULL if it is not
assigned any valid address of the memory.
• NULL pointer is a pointer which points to
nothing.
• Pointer is initialized with a value NULL or 0
regardless of the pointer type.
4/21/2021 1.5 _ Pointers Concepts 104
Example
4/21/2021 1.5 _ Pointers Concepts 105
Uses of NULL pointer
• If no valid memory address is available to store it
in a pointer, initialize a pointer with NULL.
• If pointer is used in a function block, before
using it, check whether the pointer is not a NULL
value.
• Make a habit of initializing a pointer before
using it.
• Initialize a pointer with a valid address or NULL.
4/21/2021 1.5 _ Pointers Concepts 106
Example
4/21/2021 1.5 _ Pointers Concepts 107
Pointer to a Pointer
• C supports a pointer that points to another
pointer.
• This pointer in turn can point to another
pointer, and so on.
• At the simplest level, a pointer to a pointer is
declared in this manner:
4/21/2021 1.5 _ Pointers Concepts 108
Pointer to a Pointer
4/21/2021 1.5 _ Pointers Concepts 109
Pointer to a Pointer
• This pointer currently points nowhere. It can
be completely dereferenced after
– (i) pointing q to a pointer variable, say, p, and
– (ii) pointing p to another object, say, the simple
variable x.
• Thus, if p = &x and q = &p, then the value of x
can be evaluated using double indirection:
4/21/2021 1.5 _ Pointers Concepts 110
Pointer to a Pointer
• This expression can be interpreted as *(*q),
which means using the dereferencing
operator twice.
• You need to use an extra * for every
additional level of indirection.
• Thus, you can create a pointer to q, say, r, and
then use ***r or **q or *p to evaluate x.
4/21/2021 1.5 _ Pointers Concepts 111
Example 1
4/21/2021 1.5 _ Pointers Concepts 112
Example 2
4/21/2021 1.5 _ Pointers Concepts 113
Uses and Caution of **P
• Why do we need pointer-to-pointers?
• Can a function that swaps two regular variables
be used to swap two pointers?
– No, it can’t because the function will swap the copies
of these pointers.
– The solution obviously lies in the use of pointer-to-
pointers as function arguments.
• double-indirection pointers are
– Implicitly used in handling 2D arrays.
– Explicitly used in applications that need to
manipulate pointer values inside a function.
4/21/2021 1.5 _ Pointers Concepts 114
Generic Pointer (or) void Pointer
• There is no data type associated with generic
pointer.
• It can be used to store address of any data
type and it can be converted to any type
using type casting.
• void pointers cannot be dereferenced.
• Generic pointer can be declared using the
keyword void.
4/21/2021 1.5 _ Pointers Concepts 115
Example
4/21/2021 1.5 _ Pointers Concepts 116
Dangling Pointer
4/21/2021 1.5 _ Pointers Concepts 117
• Even though the memory block is freed, it is still
accessible because the pointer to it is not lost
(dangling pointer).
• Dangling pointers arise during object destruction,
when an object that has an incoming reference is
deleted or deallocated, without modifying the value of
the pointer, so that the pointer still points to the
memory location of the deallocated memory.
Dangling Pointer
• Freeing a memory block with free(p) doesn’t
necessarily make it inaccessible because p continues
to point to the block. p is now a dangling pointer.
• As a safety measure, it should be set to NULL
immediately after invoking free.
• Because this memory—partially or totally—may have
already been allocated, a subsequent attempt to
access it using p could produce erroneous results or
even cause the program to crash.
• Setting p to NULL solves the problem easily.
4/21/2021 1.5 _ Pointers Concepts 118
Dangling Pointer
• A pointer pointing to a memory location that
has been deleted (or freed) is called dangling
pointer.
• There are three different ways where Pointer
acts as dangling pointer:
– De-allocation of memory
– Function Call
– Variable goes out of scope
4/21/2021 1.5 _ Pointers Concepts 119
Example – De-allocation of memory
4/21/2021 1.5 _ Pointers Concepts 120
Example – Function Call
4/21/2021 1.5 _ Pointers Concepts 121
Example – Function Call - Solution
4/21/2021 1.5 _ Pointers Concepts 122
Example – Variable goes out of scope
4/21/2021 1.5 _ Pointers Concepts 123
Wild Pointer
• A pointer which has not been initialized to
anything (not even NULL) is known as wild
pointer.
• The pointer may be initialized to a non-NULL
garbage value that may not be a valid address.
4/21/2021 1.5 _ Pointers Concepts 124
Thank you
4/21/2021 1.5 _ Pointers Concepts 125
UNIT I : Pointers and Arrays, Pointers
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.
20CST21 – Programming and Linear Data Structures
Unit I : Contents
1. Pointers- Introduction
2. Pointers and 1D array
3. Passing an array to a function
4. Returning an array from function
5. Pointers and 2D array
6. Array of pointers
7. NULL pointers
8. Pointer-to-pointer
9. Generic pointers
10. Dangling Pointer
11. Using Pointers for string manipulation
12. Two dimensional array of strings
13. Array of pointers to strings.
4/21/2021 127
1.6 _ Pointers and Strings
Pointers and Strings
• Strings are defined as arrays of characters.
• In order to allow variable length strings, the
string should be terminated by ‘0’ which is used
to indicate the end of a string.
• For example, the following program segment
declares a string s of 10 characters and assign the
starting address of string s into pointer ptr.
4/21/2021 1.6 _ Pointers and Strings 128
Pointers and Strings
• Three things will happen when we create the
below array.
– 10 memory locations are allocated for the array.
– The string “Hello” is stored in first 5 locations and in
the sixth location ‘0’ is automatically stored to
indicate the end of the string.
– The pointer ptr points at the first location of the
allocated memory
4/21/2021 1.6 _ Pointers and Strings 129
Example – program to use pointer to
print the string array
4/21/2021 1.6 _ Pointers and Strings 130
display the string using pointer with
“%s” as the formatting character
4/21/2021 1.6 _ Pointers and Strings 131
Example 2 - to count vowels and consonants in a string
using pointer
4/21/2021 1.6 _ Pointers and Strings 132
Example 3 - to find the length of the given string
4/21/2021 1.6 _ Pointers and Strings 133
4/21/2021 1.6 _ Pointers and Strings 134
create a list of strings
• When we want to create a list of strings, We
can use the following methods:
– Two dimensional character array
– Array of Pointers to Strings
4/21/2021 1.6 _ Pointers and Strings 135
Two dimensional character array
• The following program demonstrates the use of
2-D array to store the list of cities. It allocates
memory for storing 4 cities and for each city 10
locations are allocated.
4/21/2021 1.6 _ Pointers and Strings 136
Example 1
4/21/2021 1.6 _ Pointers and Strings 137
Example 2 - to sort the list of names in
alphabetical order
4/21/2021 1.6 _ Pointers and Strings 138
4/21/2021 1.6 _ Pointers and Strings 139
Array of Pointers to Strings
• When we want to store multiple strings, we
can create array of pointers and we can make
each pointer points to one string.
• Suppose there are N elements in an array, we
can make each element to point to one string.
4/21/2021 1.6 _ Pointers and Strings 140
Array of Pointers to Strings
• we have learned how we can use an array of
strings or 2-D array of characters.
• It may appear to you whenever you need to
store more than one string then an array of
strings is the way to go, unfortunately, this is
not the case.
• Consider the following example.
4/21/2021 1.6 _ Pointers and Strings 141
Array of Pointers to Strings
4/21/2021 1.6 _ Pointers and Strings 142
Array of Pointers to Strings
• As you can see not all strings are long enough to fill all
the rows of the array, that's why compiler fills these
empty spaces (highlighted using light grey color) with
the null characters ('0').
• The total size of the sports array is 75 bytes but
only 34 bytes is used, 41 bytes is wasted.
• 41 bytes may not appear much but in a large program,
a considerable amount of bytes would be wasted.
• What we need is a jagged array: A 2-D array whose
rows can be of different length.
• C doesn't provide jagged arrays but we can simulate
them using an array of pointer to a string.
4/21/2021 1.6 _ Pointers and Strings 143
Array of Pointers to Strings
• An array of pointers to strings is an array of
character pointers where each pointer points
to the first character of the string or the base
address of the string.
• Let's see how we can declare and initialize an
array of pointers to strings.
4/21/2021 1.6 _ Pointers and Strings 144
Array of Pointers to Strings
4/21/2021 1.6 _ Pointers and Strings 145
Array of Pointers to Strings
• Here sports is an array of pointers to strings.
• If initialization of an array is done at the time of
declaration then we can omit the size of an
array.
• So the above statement can also be written as:
4/21/2021 1.6 _ Pointers and Strings 146
Array of Pointers to Strings
• It is important to note that each element of
the sports array is a string literal and since a
string literal points to the base address of the
first character.
• The 0th element i.e arr[0] points to the base
address of string "golf".
• Similarly, the 1st element i.e arr[1] points to
the base address of string "hockey" and so on.
4/21/2021 1.6 _ Pointers and Strings 147
• Here is how an array of pointers to string is
stored in memory.
4/21/2021 1.6 _ Pointers and Strings 148
Array of Pointers to Strings
Array of Pointers to Strings
• 34 + 20 = 54.
• In this case, all string literals occupy 34 bytes
and 20 bytes are occupied by the array of
pointers i.e sports.
• So, just by creating an array of pointers to
string instead of array 2-D array of characters
we are saving 21 bytes (75-54=21) of memory
4/21/2021 1.6 _ Pointers and Strings 149
Example 1
4/21/2021 1.6 _ Pointers and Strings 150
4/21/2021 1.6 _ Pointers and Strings 151
Example 2 - Array of Pointers to Strings
• The following program demonstrates the use of
array of pointers to store the list of cities.
• Each pointer in the array can point to one city
name.
• It allocates memory for
– 1) storing the address of four strings
• ( 4 x 4 = 16 locations)
– 2) required memory locations
• (ie., Number of characters in the string + 1 location for
storing ‘0’ character) are allocated for each city.
4/21/2021 1.6 _ Pointers and Strings 152
4/21/2021 1.6 _ Pointers and Strings 153
4/21/2021 1.6 _ Pointers and Strings 154
4/21/2021 1.6 _ Pointers and Strings 155
Thank you
4/21/2021 1.6 _ Pointers and Strings 156

More Related Content

What's hot

Compiler Design
Compiler DesignCompiler Design
Compiler Design
Mir Majid
 

What's hot (20)

Data types in C
Data types in CData types in C
Data types in C
 
Structure in C
Structure in CStructure in C
Structure in C
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
List in Python
List in PythonList in Python
List in Python
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Linear search-and-binary-search
Linear search-and-binary-searchLinear search-and-binary-search
Linear search-and-binary-search
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
digital logic circuits, digital component
digital logic circuits, digital componentdigital logic circuits, digital component
digital logic circuits, digital component
 
Hashing
HashingHashing
Hashing
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Array Of Pointers
Array Of PointersArray Of Pointers
Array Of Pointers
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
 
Sparse matrix and its representation data structure
Sparse matrix and its representation data structureSparse matrix and its representation data structure
Sparse matrix and its representation data structure
 
Constants and variables in c programming
Constants and variables in c programmingConstants and variables in c programming
Constants and variables in c programming
 
Logic simplification sop and pos forms
Logic simplification sop and pos formsLogic simplification sop and pos forms
Logic simplification sop and pos forms
 
Signed Binary Numbers
Signed Binary NumbersSigned Binary Numbers
Signed Binary Numbers
 

Similar to C Programming : Pointers and Arrays, Pointers and Strings

C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
ANUSUYA S
 
Chp3(pointers ref)
Chp3(pointers ref)Chp3(pointers ref)
Chp3(pointers ref)
Mohd Effandi
 
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdf
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdfDeclaring a PointerTo define a pointer, use an asterisk, (), in t.pdf
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdf
malavshah9013
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
JoeyDelaCruz22
 
U3_4_PointerArithmetic.pdf people will use the above preaentationa dn
U3_4_PointerArithmetic.pdf people will use the above preaentationa dnU3_4_PointerArithmetic.pdf people will use the above preaentationa dn
U3_4_PointerArithmetic.pdf people will use the above preaentationa dn
mit23cs
 

Similar to C Programming : Pointers and Arrays, Pointers and Strings (20)

Pointers in c language
Pointers in c languagePointers in c language
Pointers in c language
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
 
Pointers
PointersPointers
Pointers
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 
pointers (1).ppt
pointers (1).pptpointers (1).ppt
pointers (1).ppt
 
Chp3(pointers ref)
Chp3(pointers ref)Chp3(pointers ref)
Chp3(pointers ref)
 
c++ arrays and pointers grade 9 STEP curriculum.pptx
c++ arrays and pointers grade 9 STEP curriculum.pptxc++ arrays and pointers grade 9 STEP curriculum.pptx
c++ arrays and pointers grade 9 STEP curriculum.pptx
 
Pointers
PointersPointers
Pointers
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf
 
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdf
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdfDeclaring a PointerTo define a pointer, use an asterisk, (), in t.pdf
Declaring a PointerTo define a pointer, use an asterisk, (), in t.pdf
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointers
PointersPointers
Pointers
 
Pointer
PointerPointer
Pointer
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
 
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...
 
U3_4_PointerArithmetic.pdf people will use the above preaentationa dn
U3_4_PointerArithmetic.pdf people will use the above preaentationa dnU3_4_PointerArithmetic.pdf people will use the above preaentationa dn
U3_4_PointerArithmetic.pdf people will use the above preaentationa dn
 

More from Selvaraj Seerangan

Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Selvaraj Seerangan
 
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
Selvaraj Seerangan
 

More from Selvaraj Seerangan (20)

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

Recently uploaded

Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
dharasingh5698
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 

C Programming : Pointers and Arrays, Pointers and Strings

  • 1. UNIT I : Pointers and Arrays, Pointers 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. 20CST21 – Programming and Linear Data Structures
  • 2. Preamble and Course Outcomes 4/21/2021 1.0 _ Pointers and Arrays 2
  • 3. Syllabus – Unit Wise 4/21/2021 1.0 _ Pointers and Arrays 3
  • 4. List of Exercises 4/21/2021 1.0 _ Pointers and Arrays 4
  • 5. Text Book and Reference Book 4/21/2021 1.0 _ Pointers and Arrays 5
  • 6. Unit I : Contents 1. Pointers- Introduction 2. Pointers and 1D array 3. Passing an array to a function 4. Returning an array from function 5. NULL pointers 6. Array of pointers 7. Pointer-to-pointer 8. Pointers and 2D array 9. Generic pointers 10. Dangling Pointer 11. Using Pointers for string manipulation 12. Two dimensional array of strings 13. Array of pointers to strings. 4/21/2021 6 1.0 _ Pointers and Arrays
  • 7. Pointers- Introduction • Every variable in C language has a name and a value associated with it. • When a variable is declared, a specific block of memory within the computer is allocated to hold the value of that variable. • Each memory location has a distinct address. 4/21/2021 1.0 _ Pointers and Arrays 7
  • 8. Pointers- Introduction • For example, – we live in a house and our house has an address, which helps other people to identify our house. • The same way the value of the variable is identified using the address of that variable. • This address of the variable or memory location can be stored in a pointer. 4/21/2021 1.0 _ Pointers and Arrays 8
  • 9. Pointers- Introduction • Using pointer we can have direct access to a memory location because they store address of a variable or memory location. • Pointers are closely related to low level memory operations. • Before introducing the pointers in programming, let us understand what happens during a variable definition. 4/21/2021 1.0 _ Pointers and Arrays 9
  • 10. Pointers- Introduction • Let us consider the following statement : • When the above statement is compiled and executed, the following will happen: – The compiler allocates memory to store an integer. – Next , compiler assigns a label to the allocated memory location as n. – Finally, the constant 10 is stored in that location. 4/21/2021 1.0 _ Pointers and Arrays 10
  • 11. Advantages of Pointers • Pointers provide direct access to memory. • Pointers are used to return more than one value from a function. • Pointers allow dynamic memory allocation and deallocation. • Reduces the storage space required by the program. • Pointers are more efficient in handling arrays and structures. • Pointers are used to get reference of a variable or function. • Pointers increases program execution speed. • Pointer allows to create complex data structures such as linked list, stack, queues, trees, graphs etc. 4/21/2021 1.0 _ Pointers and Arrays 11
  • 12. Pointers- Introduction • Pointer is a variable which stores the address of another variable. • It is used to allocate memory dynamically. • Memory allocation done at run time is known as Dynamic memory allocation. • Pointer variable may be any valid C data type such as int, float, double, char etc. • For any type of pointers, only four bytes of memory is allocated for storing the address. 4/21/2021 1.0 _ Pointers and Arrays 12
  • 13. Example 4/21/2021 1.0 _ Pointers and Arrays 13
  • 14. Pointer Declaration 4/21/2021 1.0 _ Pointers and Arrays 14 • Pointer can be declared with a variable preceded by *. • Pointer can be declared using the following syntax:
  • 15. Pointer operators • Reference or Address of operator (&) • Dereference operator or indirection operator or Value at Address Operator (*) 4/21/2021 1.0 _ Pointers and Arrays 15
  • 16. Reference Operator - Example 4/21/2021 1.0 _ Pointers and Arrays 16
  • 17. Dereference operator (*) • To access the value at the address stored in the pointer variable, we can use dereference operator (*). • This is an unary operator * that returns the value of the variable located at the address specified by its operand. 4/21/2021 1.0 _ Pointers and Arrays 17
  • 18. Dereference Operator - Example 4/21/2021 1.0 _ Pointers and Arrays 18
  • 19. Example 1 4/21/2021 1.0 _ Pointers and Arrays 19
  • 20. 4/21/2021 1.0 _ Pointers and Arrays 20
  • 21. Swapping using function and pointers • we have to use pointers concept. • Bz, – Parameters are always passed by value in C and – function can not return more than one value. 4/21/2021 1.0 _ Pointers and Arrays 21
  • 22. Example 2 4/21/2021 1.0 _ Pointers and Arrays 22
  • 23. Example 3 4/21/2021 1.0 _ Pointers and Arrays 23
  • 24. Pointer Arithmetic • A pointer is a variable which holds the address of another variable. • Address is represented by a numeric value. • We cannot perform every type of arithmetic operation on pointers. • The following arithmetic operations are the only valid arithmetic operations performed on pointers: 4/21/2021 1.0 _ Pointers and Arrays 24
  • 25. Pointer Arithmetic • For example, assume the integer pointer ptr which contains the address 1000. • If we are incrementing the pointer ptr by 1 (using ++ptr or ptr++), we will get 1002 (i.e 1000 + 1 * 2) • Instead of 1001 because the size of the int data type is 2 bytes (Note: Size of the datatype changes depends on the compiler used). • If we are using a system where the size of int is 4 bytes then we would get 1004 ( i.e 1000 + 1 * 4 ). 4/21/2021 1.0 _ Pointers and Arrays 25
  • 26. Pointer Arithmetic - Example • Suppose the address of the variables i, f and ch are 1000, 2000 , 3000 respectively. Therefore iptr, fptr and cptr will have initial values of 1000, 2000 and 3000. Assume 1, 2 and 4 bytes of memory is allocated for char, int and float variables respectively. 4/21/2021 1.0 _ Pointers and Arrays 26
  • 27. 4/21/2021 1.0 _ Pointers and Arrays 27
  • 28. 4/21/2021 1.0 _ Pointers and Arrays 28
  • 29. 4/21/2021 1.0 _ Pointers and Arrays 29
  • 30. Example 4 - Print all the alphabets using pointer 4/21/2021 1.0 _ Pointers and Arrays 30
  • 31. Example 5 - Add two integers using pointers 4/21/2021 1.0 _ Pointers and Arrays 31
  • 32. Example 6 - Add two integers using function by passing address of two numbers as arguments to function. 4/21/2021 1.0 _ Pointers and Arrays 32
  • 33. Pointer Arithmetic between Two Pointers • Arithmetic operation between two pointers is performed only on same type of pointers. • Let us take two integer pointers ptr1 and ptr2 with addresses 1000 and 1008 respectively. • The expression ptr2 - ptr1 will give the result as 4, since the memory location allocated for integer data type is 2 bytes. • If we subtract ptr2 from ptr1 i.e the expression (ptr1 - ptr2) will give the result -4. 4/21/2021 1.0 _ Pointers and Arrays 33
  • 34. Example 7 4/21/2021 1.0 _ Pointers and Arrays 34
  • 35. Thank you 4/21/2021 1.0 _ Pointers and Arrays 35
  • 36. UNIT I : Pointers and Arrays, Pointers 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. 20CST21 – Programming and Linear Data Structures
  • 37. Unit I : Contents 1. Pointers- Introduction 2. Pointers and 1D array 3. Passing an array to a function 4. Returning an array from function 5. NULL pointers 6. Array of pointers 7. Pointer-to-pointer 8. Pointers and 2D array 9. Generic pointers 10. Dangling Pointer 11. Using Pointers for string manipulation 12. Two dimensional array of strings 13. Array of pointers to strings. 4/21/2021 37 2.0 _ Pointers and Arrays
  • 38. Pointers and Arrays • We are already familiar with arrays, which store multiple values of the same data type. • Array elements are stored in contiguous memory locations. • When an array is declared, compiler allocates required amount of contiguous memory locations to hold all the elements of the array. • Memory is allocated by the compiler during compilation time itself. • Base address of the array is the address of the first element of the array. • We can create a pointer which can be used to point an array. • In an one dimensional array, we can use single subscript to access the array elements. • Name of the 1-D array or &array[0] points to the address of the first element of an array. 4/21/2021 2.0 _ Pointers and Arrays 38
  • 39. Pointers and 1D Arrays • Suppose we declare an integer array “A” with 5 elements and assuming that the base address of the array a is 1000 and each integer element requires two bytes of memory. • The five elements will be stored as follows: • Here array name “A” acts as a constant pointer which will give the base address of the array and points to the first element of the array, A[0]. – i.e., the value of A and &A[0] are same. 4/21/2021 2.0 _ Pointers and Arrays 39
  • 40. Pointers and 1D Arrays • We can declare another pointer of type int to point to the array A. • Now we can access every element of the array A using pointer p. • (*p) is used to access the element A[0] which has the value 1 in the given example. • To access the next element in the array A, – increment the pointer p by 1 using (p++) or (++p). – Now we can give *p to get A[1]. – It gives the value 2. – To get the next element in the array A, increment the pointer p by 1 and use *p. 4/21/2021 2.0 _ Pointers and Arrays 40
  • 41. Example 1- Program to demonstrates the use of pointer to access the array elements 4/21/2021 2.0 _ Pointers and Arrays 41
  • 42. Example 2- use array name as a pointer to access the array elements 4/21/2021 2.0 _ Pointers and Arrays 42
  • 43. • In the above program, A is a constant pointer which always points to first element A[0]. • We cannot move this pointer to next element using ++ operator since base address of the array cannot be changed. • To access the elements of the array using a constant pointer A, we can use the following statements: 4/21/2021 2.0 _ Pointers and Arrays 43
  • 44. Example 3- Program to display the elements of an array in reverse order using pointer. 4/21/2021 2.0 _ Pointers and Arrays 44
  • 45. Example 4 – Program to add the elements of an array using pointer 4/21/2021 2.0 _ Pointers and Arrays 45
  • 46. Example 5 – Program to demonstrate increment and decrement operators with pointers and arrays. 4/21/2021 2.0 _ Pointers and Arrays 46
  • 47. Example 6 - Program to copy an array to another array using pointers 4/21/2021 2.0 _ Pointers and Arrays 47
  • 48. Thank you 4/21/2021 2.0 _ Pointers and Arrays 48
  • 49. UNIT I : Pointers and Arrays, Pointers 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. 20CST21 – Programming and Linear Data Structures
  • 50. Unit I : Contents 1. Pointers- Introduction 2. Pointers and 1D array 3. Passing an array to a function 4. Returning an array from function 5. Pointers and 2D array 6. NULL pointers 7. Array of pointers 8. Pointer-to-pointer 9. Generic pointers 10. Dangling Pointer 11. Using Pointers for string manipulation 12. Two dimensional array of strings 13. Array of pointers to strings. 4/21/2021 50 2.0 _ Passing and Returing an array to_from a function
  • 51. Passing an array to a function • We can pass an individual elements or entire array to a function as an argument. • To pass an entire array to a function, only the name of the array is passed as an argument. • When address is passed as an argument, the function definition should have an array or a pointer as a parameter to receive the passed address. • When an array is passed to a function, the changes made by the function affect the original array. 4/21/2021 2.0 _ Passing and Returing an array to_from a function 51
  • 52. Function Definition with array as a parameter • We can receive an array in a function using one of the following two methods. • The name of the array is passes as an argument, which is the address of the first element of the array. 4/21/2021 2.0 _ Passing and Returing an array to_from a function 52
  • 53. Example 1 – Program to demonstrate the average of all the elements of an array. 4/21/2021 2.0 _ Passing and Returing an array to_from a function 53
  • 54. Method 1 4/21/2021 2.0 _ Passing and Returing an array to_from a function 54
  • 55. Method 2 4/21/2021 2.0 _ Passing and Returing an array to_from a function 55
  • 56. Method 3 4/21/2021 2.0 _ Passing and Returing an array to_from a function 56
  • 57. Example 2 - Write a program in C to sort an array using Pointer 4/21/2021 2.0 _ Passing and Returing an array to_from a function 57
  • 58. Returning an array from a function • C does not allow to return an entire array from a function. • However, we can return a pointer to the base address(address of first element of array) of an array by specifying the name of the array without an index. 4/21/2021 2.0 _ Passing and Returing an array to_from a function 58
  • 59. Returning an array from a function • If we want to return a 1-D array from a function, we have to declare a function returning a pointer as in the following example : 4/21/2021 2.0 _ Passing and Returing an array to_from a function 59
  • 60. Returning an array from a function • We should not return base pointer of a local array declared inside a function because as soon as control returns from a function all local variables gets destroyed. • If we want to return a local array then we should declare it as a static variable so that it retains it's value after function call. 4/21/2021 2.0 _ Passing and Returing an array to_from a function 60
  • 61. Example 2 - Program to generate first N even numbers and return as an array. 4/21/2021 2.0 _ Passing and Returing an array to_from a function 61
  • 62. 4/21/2021 2.0 _ Passing and Returing an array to_from a function 62
  • 63. Thank you 4/21/2021 2.0 _ Passing and Returing an array to_from a function 63
  • 64. UNIT I : Pointers and Arrays, Pointers 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. 20CST21 – Programming and Linear Data Structures
  • 65. Unit I : Contents 1. Pointers- Introduction 2. Pointers and 1D array 3. Passing an array to a function 4. Returning an array from function 5. Pointers and 2D array 6. Array of pointers 7. NULL pointers 8. Pointer-to-pointer 9. Generic pointers 10. Dangling Pointer 11. Using Pointers for string manipulation 12. Two dimensional array of strings 13. Array of pointers to strings. 4/21/2021 65 1.4 _ Pointers and 2D Arrays
  • 66. Pointers and 2D array • In a two dimensional array, we can access each element by using two subscripts. – first subscript represents the row number and – second subscript represents the column number • Consider the following declaration statement, 4/21/2021 1.4 _ Pointers and 2D Arrays 66
  • 67. Pointers and 2D array • The above declaration statement creates a 3x4 matrix initialized with the following values: 4/21/2021 1.4 _ Pointers and 2D Arrays 67
  • 68. Pointers and 2D array • The element at ith row, jth column can be accessed using a[i][j]. • To access the value 7, we have to use a[1][2]. • Let us see how pointer is used to access the 2-D array. • As we know, name of the array gives the base address of the array i.e., address of a[0][0]. • To access a[i][j] using base pointer of the array, we can use the following generalized form: 4/21/2021 1.4 _ Pointers and 2D Arrays 68
  • 69. Pointers and 2D array • The following figure shows how the above 2-D array will be stored in memory. • Array elements are stored in memory row by row. 4/21/2021 1.4 _ Pointers and 2D Arrays 69
  • 70. Pointers and 2D array • In a 2-D array, each row will be considered as a one dimensional array. • Hence 2-D array can be considered as a collection of several one dimensional arrays. • In this example, each row is an array of 4 integers. • We know that the name of an array is a constant pointer that points to 0th row which contains address 1000. 4/21/2021 1.4 _ Pointers and 2D Arrays 70
  • 71. Pointers and 2D array 4/21/2021 1.4 _ Pointers and 2D Arrays 71
  • 72. Pointers and 2D array • Consider a two dimensional array mat[ROWS] [COLS] where ROWS and COLS are some integer value. • We can use any one of the following two notations to access the two dimensional array. • The first int mat[][COLS] is general array notation. • Whereas int (*mat)[COLS] is a pointer to array. 4/21/2021 1.4 _ Pointers and 2D Arrays 72
  • 73. Example - read and display a 3x3 matrix 4/21/2021 1.4 _ Pointers and 2D Arrays 73
  • 74. Passing a 2D array to a function • For passing multidimensional arrays, – First array dimension does not have to be specified. – The second dimension must be explicitly specified or a pointer to pointer as a parameter to receive the address. 4/21/2021 1.4 _ Pointers and 2D Arrays 74
  • 75. Example - print 2-D array using function 4/21/2021 1.4 _ Pointers and 2D Arrays 75
  • 76. Example - add two 3 x 3 matrices using pointer 4/21/2021 1.4 _ Pointers and 2D Arrays 76
  • 77. 4/21/2021 1.4 _ Pointers and 2D Arrays 77
  • 78. 4/21/2021 1.4 _ Pointers and 2D Arrays 78
  • 79. 4/21/2021 1.4 _ Pointers and 2D Arrays 79
  • 80. 4/21/2021 1.4 _ Pointers and 2D Arrays 80
  • 81. Example - display Lower triangular and Upper triangular of a given matrix of size mxn 4/21/2021 1.4 _ Pointers and 2D Arrays 81
  • 82. 4/21/2021 1.4 _ Pointers and 2D Arrays 82
  • 83. 4/21/2021 1.4 _ Pointers and 2D Arrays 83
  • 84. 4/21/2021 1.4 _ Pointers and 2D Arrays 84
  • 85. 4/21/2021 1.4 _ Pointers and 2D Arrays 85
  • 86. Example - to print and find sum of diagonal elements of a given matrix. 4/21/2021 1.4 _ Pointers and 2D Arrays 86
  • 87. 4/21/2021 1.4 _ Pointers and 2D Arrays 87
  • 88. 4/21/2021 1.4 _ Pointers and 2D Arrays 88
  • 89. 4/21/2021 1.4 _ Pointers and 2D Arrays 89
  • 90. 4/21/2021 1.4 _ Pointers and 2D Arrays 90
  • 91. Returning a 2D array from Function • Returning a 2D array from function is not as straight as passing an array to a function. • Arrays in C are passed by reference, hence any changes made to array passed as argument persists after the function. • So you can accept the output array you need to return, as a parameter to the function. • The following program demonstrates how a 2-D array is returned from a function by passing resultant array also as a parameter. • In the following program, main() receives two matrices as input and these two matrices along with resultant matrix are passed as arguments to the function sum(). • The sum() function adds the two matrices and return the resultant matrix as result to the main() function. 4/21/2021 1.4 _ Pointers and 2D Arrays 91
  • 92. 4/21/2021 1.4 _ Pointers and 2D Arrays 92
  • 93. 4/21/2021 1.4 _ Pointers and 2D Arrays 93
  • 94. 4/21/2021 1.4 _ Pointers and 2D Arrays 94
  • 95. 4/21/2021 1.4 _ Pointers and 2D Arrays 95
  • 96. 4/21/2021 1.4 _ Pointers and 2D Arrays 96
  • 97. Further Reference To Pass and Return an array(1D & 2D) to / from function with/without using pointers please refer this link...... • https://codeforwin.org/2017/12/pass-return- array-function-c.html#return-array-multi 4/21/2021 1.4 _ Pointers and 2D Arrays 97
  • 98. Thank you 4/21/2021 1.4 _ Pointers and 2D Arrays 98
  • 99. UNIT I : Pointers and Arrays, Pointers 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. 20CST21 – Programming and Linear Data Structures
  • 100. Unit I : Contents 1. Pointers- Introduction 2. Pointers and 1D array 3. Passing an array to a function 4. Returning an array from function 5. Pointers and 2D array 6. Array of pointers 7. NULL pointers 8. Pointer-to-pointer 9. Generic pointers 10. Dangling Pointer 11. Using Pointers for string manipulation 12. Two dimensional array of strings 13. Array of pointers to strings. 4/21/2021 100 1.5 _ Pointers Concepts
  • 101. Array of Pointers • When we want to maintain an array to store the address of memory locations of type int or float or char or any other data type available, we have to create an array of pointers. • Here is the syntax to declare an array of pointers which is almost same as that of declaring an array of int, float or char etc., 4/21/2021 1.5 _ Pointers Concepts 101
  • 102. Array of Pointers • Here ptr is an array of 5 integer pointers ie., the integer pointers are ptr[0], ptr[1] ….ptr[4]. • Each element in this array can hold the address of an integer variable. 4/21/2021 1.5 _ Pointers Concepts 102
  • 103. Example 4/21/2021 1.5 _ Pointers Concepts 103
  • 104. NULL Pointer • Pointer is assigned a value NULL if it is not assigned any valid address of the memory. • NULL pointer is a pointer which points to nothing. • Pointer is initialized with a value NULL or 0 regardless of the pointer type. 4/21/2021 1.5 _ Pointers Concepts 104
  • 105. Example 4/21/2021 1.5 _ Pointers Concepts 105
  • 106. Uses of NULL pointer • If no valid memory address is available to store it in a pointer, initialize a pointer with NULL. • If pointer is used in a function block, before using it, check whether the pointer is not a NULL value. • Make a habit of initializing a pointer before using it. • Initialize a pointer with a valid address or NULL. 4/21/2021 1.5 _ Pointers Concepts 106
  • 107. Example 4/21/2021 1.5 _ Pointers Concepts 107
  • 108. Pointer to a Pointer • C supports a pointer that points to another pointer. • This pointer in turn can point to another pointer, and so on. • At the simplest level, a pointer to a pointer is declared in this manner: 4/21/2021 1.5 _ Pointers Concepts 108
  • 109. Pointer to a Pointer 4/21/2021 1.5 _ Pointers Concepts 109
  • 110. Pointer to a Pointer • This pointer currently points nowhere. It can be completely dereferenced after – (i) pointing q to a pointer variable, say, p, and – (ii) pointing p to another object, say, the simple variable x. • Thus, if p = &x and q = &p, then the value of x can be evaluated using double indirection: 4/21/2021 1.5 _ Pointers Concepts 110
  • 111. Pointer to a Pointer • This expression can be interpreted as *(*q), which means using the dereferencing operator twice. • You need to use an extra * for every additional level of indirection. • Thus, you can create a pointer to q, say, r, and then use ***r or **q or *p to evaluate x. 4/21/2021 1.5 _ Pointers Concepts 111
  • 112. Example 1 4/21/2021 1.5 _ Pointers Concepts 112
  • 113. Example 2 4/21/2021 1.5 _ Pointers Concepts 113
  • 114. Uses and Caution of **P • Why do we need pointer-to-pointers? • Can a function that swaps two regular variables be used to swap two pointers? – No, it can’t because the function will swap the copies of these pointers. – The solution obviously lies in the use of pointer-to- pointers as function arguments. • double-indirection pointers are – Implicitly used in handling 2D arrays. – Explicitly used in applications that need to manipulate pointer values inside a function. 4/21/2021 1.5 _ Pointers Concepts 114
  • 115. Generic Pointer (or) void Pointer • There is no data type associated with generic pointer. • It can be used to store address of any data type and it can be converted to any type using type casting. • void pointers cannot be dereferenced. • Generic pointer can be declared using the keyword void. 4/21/2021 1.5 _ Pointers Concepts 115
  • 116. Example 4/21/2021 1.5 _ Pointers Concepts 116
  • 117. Dangling Pointer 4/21/2021 1.5 _ Pointers Concepts 117 • Even though the memory block is freed, it is still accessible because the pointer to it is not lost (dangling pointer). • Dangling pointers arise during object destruction, when an object that has an incoming reference is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.
  • 118. Dangling Pointer • Freeing a memory block with free(p) doesn’t necessarily make it inaccessible because p continues to point to the block. p is now a dangling pointer. • As a safety measure, it should be set to NULL immediately after invoking free. • Because this memory—partially or totally—may have already been allocated, a subsequent attempt to access it using p could produce erroneous results or even cause the program to crash. • Setting p to NULL solves the problem easily. 4/21/2021 1.5 _ Pointers Concepts 118
  • 119. Dangling Pointer • A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer. • There are three different ways where Pointer acts as dangling pointer: – De-allocation of memory – Function Call – Variable goes out of scope 4/21/2021 1.5 _ Pointers Concepts 119
  • 120. Example – De-allocation of memory 4/21/2021 1.5 _ Pointers Concepts 120
  • 121. Example – Function Call 4/21/2021 1.5 _ Pointers Concepts 121
  • 122. Example – Function Call - Solution 4/21/2021 1.5 _ Pointers Concepts 122
  • 123. Example – Variable goes out of scope 4/21/2021 1.5 _ Pointers Concepts 123
  • 124. Wild Pointer • A pointer which has not been initialized to anything (not even NULL) is known as wild pointer. • The pointer may be initialized to a non-NULL garbage value that may not be a valid address. 4/21/2021 1.5 _ Pointers Concepts 124
  • 125. Thank you 4/21/2021 1.5 _ Pointers Concepts 125
  • 126. UNIT I : Pointers and Arrays, Pointers 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. 20CST21 – Programming and Linear Data Structures
  • 127. Unit I : Contents 1. Pointers- Introduction 2. Pointers and 1D array 3. Passing an array to a function 4. Returning an array from function 5. Pointers and 2D array 6. Array of pointers 7. NULL pointers 8. Pointer-to-pointer 9. Generic pointers 10. Dangling Pointer 11. Using Pointers for string manipulation 12. Two dimensional array of strings 13. Array of pointers to strings. 4/21/2021 127 1.6 _ Pointers and Strings
  • 128. Pointers and Strings • Strings are defined as arrays of characters. • In order to allow variable length strings, the string should be terminated by ‘0’ which is used to indicate the end of a string. • For example, the following program segment declares a string s of 10 characters and assign the starting address of string s into pointer ptr. 4/21/2021 1.6 _ Pointers and Strings 128
  • 129. Pointers and Strings • Three things will happen when we create the below array. – 10 memory locations are allocated for the array. – The string “Hello” is stored in first 5 locations and in the sixth location ‘0’ is automatically stored to indicate the end of the string. – The pointer ptr points at the first location of the allocated memory 4/21/2021 1.6 _ Pointers and Strings 129
  • 130. Example – program to use pointer to print the string array 4/21/2021 1.6 _ Pointers and Strings 130
  • 131. display the string using pointer with “%s” as the formatting character 4/21/2021 1.6 _ Pointers and Strings 131
  • 132. Example 2 - to count vowels and consonants in a string using pointer 4/21/2021 1.6 _ Pointers and Strings 132
  • 133. Example 3 - to find the length of the given string 4/21/2021 1.6 _ Pointers and Strings 133
  • 134. 4/21/2021 1.6 _ Pointers and Strings 134
  • 135. create a list of strings • When we want to create a list of strings, We can use the following methods: – Two dimensional character array – Array of Pointers to Strings 4/21/2021 1.6 _ Pointers and Strings 135
  • 136. Two dimensional character array • The following program demonstrates the use of 2-D array to store the list of cities. It allocates memory for storing 4 cities and for each city 10 locations are allocated. 4/21/2021 1.6 _ Pointers and Strings 136
  • 137. Example 1 4/21/2021 1.6 _ Pointers and Strings 137
  • 138. Example 2 - to sort the list of names in alphabetical order 4/21/2021 1.6 _ Pointers and Strings 138
  • 139. 4/21/2021 1.6 _ Pointers and Strings 139
  • 140. Array of Pointers to Strings • When we want to store multiple strings, we can create array of pointers and we can make each pointer points to one string. • Suppose there are N elements in an array, we can make each element to point to one string. 4/21/2021 1.6 _ Pointers and Strings 140
  • 141. Array of Pointers to Strings • we have learned how we can use an array of strings or 2-D array of characters. • It may appear to you whenever you need to store more than one string then an array of strings is the way to go, unfortunately, this is not the case. • Consider the following example. 4/21/2021 1.6 _ Pointers and Strings 141
  • 142. Array of Pointers to Strings 4/21/2021 1.6 _ Pointers and Strings 142
  • 143. Array of Pointers to Strings • As you can see not all strings are long enough to fill all the rows of the array, that's why compiler fills these empty spaces (highlighted using light grey color) with the null characters ('0'). • The total size of the sports array is 75 bytes but only 34 bytes is used, 41 bytes is wasted. • 41 bytes may not appear much but in a large program, a considerable amount of bytes would be wasted. • What we need is a jagged array: A 2-D array whose rows can be of different length. • C doesn't provide jagged arrays but we can simulate them using an array of pointer to a string. 4/21/2021 1.6 _ Pointers and Strings 143
  • 144. Array of Pointers to Strings • An array of pointers to strings is an array of character pointers where each pointer points to the first character of the string or the base address of the string. • Let's see how we can declare and initialize an array of pointers to strings. 4/21/2021 1.6 _ Pointers and Strings 144
  • 145. Array of Pointers to Strings 4/21/2021 1.6 _ Pointers and Strings 145
  • 146. Array of Pointers to Strings • Here sports is an array of pointers to strings. • If initialization of an array is done at the time of declaration then we can omit the size of an array. • So the above statement can also be written as: 4/21/2021 1.6 _ Pointers and Strings 146
  • 147. Array of Pointers to Strings • It is important to note that each element of the sports array is a string literal and since a string literal points to the base address of the first character. • The 0th element i.e arr[0] points to the base address of string "golf". • Similarly, the 1st element i.e arr[1] points to the base address of string "hockey" and so on. 4/21/2021 1.6 _ Pointers and Strings 147
  • 148. • Here is how an array of pointers to string is stored in memory. 4/21/2021 1.6 _ Pointers and Strings 148 Array of Pointers to Strings
  • 149. Array of Pointers to Strings • 34 + 20 = 54. • In this case, all string literals occupy 34 bytes and 20 bytes are occupied by the array of pointers i.e sports. • So, just by creating an array of pointers to string instead of array 2-D array of characters we are saving 21 bytes (75-54=21) of memory 4/21/2021 1.6 _ Pointers and Strings 149
  • 150. Example 1 4/21/2021 1.6 _ Pointers and Strings 150
  • 151. 4/21/2021 1.6 _ Pointers and Strings 151
  • 152. Example 2 - Array of Pointers to Strings • The following program demonstrates the use of array of pointers to store the list of cities. • Each pointer in the array can point to one city name. • It allocates memory for – 1) storing the address of four strings • ( 4 x 4 = 16 locations) – 2) required memory locations • (ie., Number of characters in the string + 1 location for storing ‘0’ character) are allocated for each city. 4/21/2021 1.6 _ Pointers and Strings 152
  • 153. 4/21/2021 1.6 _ Pointers and Strings 153
  • 154. 4/21/2021 1.6 _ Pointers and Strings 154
  • 155. 4/21/2021 1.6 _ Pointers and Strings 155
  • 156. Thank you 4/21/2021 1.6 _ Pointers and Strings 156