SlideShare a Scribd company logo
1 of 85
C Programming
Module 6
Pointers
Ms. Surekha Mali
19 September 2022 2
Introduction
• A pointer is a variable that represents the
location (rather than the value) of a data item.
• They have a number of useful applications.
– Enables us to access a variable that is defined
outside the function.
– Can be used to pass information back and forth
between a function and its reference point.
– More efficient in handling data tables.
– Reduces the length and complexity of a program.
– Sometimes also increases the execution speed.
Ms. Surekha Mali
19 September 2022 3
Basic Concept
• Within the computer memory, every stored data
item occupies one or more contiguous memory
cells.
– The number of memory cells required to store a data
item depends on its type (char, int, double, etc.).
• Whenever we declare a variable, the system
allocates memory location(s) to hold the value of
the variable.
– Since every byte in memory has a unique address, this
location will also have its own (unique) address.
Ms. Surekha Mali
19 September 2022 4
Continue.....Example
Ms. Surekha Mali
Int *p , number;
P=&number;
19 September 2022 5
Continue.....
• Consider the statement
int xyz = 50;
– This statement instructs the compiler to allocate a
location for the integer variable xyz, and put the
value 50 in that location.
– Suppose that the address location chosen is 1380.
xyz  variable
50  value
1380  address
Ms. Surekha Mali
19 September 2022 Ms. Surekha Mali 6
Continue.....
• During execution of the program, the system
always associates the name xyz with the
address 1380.
– The value 50 can be accessed by using either the
name xyz or the address 1380.
• Since memory addresses are simply numbers,
they can be assigned to some variables which
can be stored in memory.
– Such variables that hold memory addresses are
called pointers.
– Since a pointer is a variable, its value is also stored
in some memory location.
19 September 2022 Ms. Surekha Mali 7
Continue.....
• Suppose we assign the address of xyz to a
variable p.
– p is said to point to the variable xyz.
Variable Value Address
xyz 50 1380
p 1380 2545
p = &xyz;
50
1380
xyz
1380
2545
p
19 September 2022 Ms. Surekha Mali 8
Accessing the Address of a Variable
• The address of a variable can be determined
using the ‘&’ operator.
– The operator ‘&’ immediately preceding a variable
returns the address of the variable.
• Example:
p = &xyz;
– The address of xyz (1380) is assigned to p.
• The ‘&’ operator can be used only with a
simple variable or an array element.
&distance
&x[0]
&x[i-2]
19 September 2022 Ms. Surekha Mali 9
Continue.....
• Following usages are illegal:
&235
• Pointing at constant.
int arr[20];
:
&arr;
• Pointing at array name.
&(a+b)
• Pointing at expression.
19 September 2022 Ms. Surekha Mali 10
Example
#include <stdio.h>
main()
{
int a;
float b, c;
double d;
char ch;
a = 10; b = 2.5; c = 12.36; d = 12345.66; ch = ‘A’;
printf (“%d is stored in location %u n”, a, &a) ;
printf (“%f is stored in location %u n”, b, &b) ;
printf (“%f is stored in location %u n”, c, &c) ;
printf (“%ld is stored in location %u n”, d, &d) ;
printf (“%c is stored in location %u n”, ch, &ch) ;
}
19 September 2022 Ms. Surekha Mali 11
Output:
10 is stored in location 3221224908
2.500000 is stored in location 3221224904
12.360000 is stored in location 3221224900
12345.660000 is stored in location 3221224892
A is stored in location 3221224891
Incidentally variables a,b,c,d and ch are allocated
to contiguous memory locations.
a
b
c
d
ch
19 September 2022 Ms. Surekha Mali 12
Pointer Declarations
• Pointer variables must be declared before we
use them.
• General form:
data_type *pointer_name;
Three things are specified in the above
declaration:
1. The asterisk (*) tells that the variable pointer_name is a
pointer variable.
2. pointer_name needs a memory location.
3. pointer_name points to a variable of type data_type.
19 September 2022 Ms. Surekha Mali 13
Continue.....
• Example:
int *count;
float *speed;
• Once a pointer variable has been declared, it
can be made to point to a variable using an
assignment statement like:
int *p, xyz;
:
p = &xyz;
– This is called pointer initialization.
19 September 2022 Ms. Surekha Mali 14
Things to Remember
• Pointer variables must always point to a data
item of the same type.
float x;
int *p;
:  will result in erroneous output
p = &x;
• Assigning an absolute address to a pointer
variable is prohibited.
int *count;
:
count = 1268;
19 September 2022 Ms. Surekha Mali 15
Accessing a Variable Through its Pointer
• Once a pointer has been assigned the address of
a variable, the value of the variable can be
accessed using the indirection operator (*).
int a, b;
int *p;
:
p = &a;
b = *p;
Equivalent to b = a
19 September 2022 Ms. Surekha Mali 16
Example 1
#include <stdio.h>
main()
{
int a, b;
int c = 5;
int *p;
a = 4 * (c + 5) ;
p = &c;
b = 4 * (*p + 5) ;
printf (“a=%d b=%d n”, a, b) ;
}
Equivalent
19 September 2022 Ms. Surekha Mali 17
Example 2
#include <stdio.h>
main()
{
int x, y;
int *ptr;
x = 10 ;
ptr = &x ;
y = *ptr ;
printf (“%d is stored in location %u n”, x, &x) ;
printf (“%d is stored in location %u n”, *&x, &x) ;
printf (“%d is stored in location %u n”, *ptr, ptr) ;
printf (“%d is stored in location %u n”, y, &*ptr) ;
printf (“%u is stored in location %u n”, ptr, &ptr) ;
printf (“%d is stored in location %u n”, y, &y) ;
*ptr = 25;
printf (“nNow x = %d n”, x);
}
*&xx
ptr=&x;
&x&*ptr
19 September 2022 Ms. Surekha Mali 18
Output:
10 is stored in location 3221224908
10 is stored in location 3221224908
10 is stored in location 3221224908
10 is stored in location 3221224908
3221224908 is stored in location 3221224900
10 is stored in location 3221224904
Now x = 25
Address of x: 3221224908
Address of y: 3221224904
Address of ptr: 3221224900
19 September 2022 Ms. Surekha Mali 19
1.#include<stdio.h>
2.int main(){
3.int number=50;
4.int *p;
5.p=&number;//stores the address of number variable
6.printf("Address of p variable is %x n",p); // p contains the address of the nu
mber therefore printing p gives the address of number.
7.printf("Value of p variable is %d n",*p); // As we know that * is used to deref
erence a pointer therefore if we print *p, we will get the value stored at the ad
dress contained by p.
8.return 0;
9.}
Example 3
19 September 2022 Ms. Surekha Mali 20
Pointer Expressions
• Like other variables, pointer variables can be
used in expressions.
• If p1 and p2 are two pointers, the following
statements are valid:
sum = *p1 + *p2 ;
prod = *p1 * *p2 ;
prod = (*p1) * (*p2) ;
*p1 = *p1 + 2;
x = *p1 / *p2 + 5 ;
19 September 2022 Ms. Surekha Mali 21
Continue.....
• What are allowed in C?
– Add an integer to a pointer.
– Subtract an integer from a pointer.
– Subtract one pointer from another (related).
• If p1 and p2 are both pointers to the same array, them
p2–p1 gives the number of elements between p1 and p2.
• What are not allowed?
– Add two pointers.
p1 = p1 + p2 ;
– Multiply / divide a pointer in an expression.
p1 = p2 / 5 ;
p1 = p1 – p2 * 10 ;
19 September 2022 22
Scale Factor
• We have seen that an integer value can be
added to or subtracted from a pointer variable.
int *p1, *p2 ;
int i, j;
:
p1 = p1 + 1 ;
p2 = p1 + j ;
p2++ ;
p2 = p2 – (i + j) ;
• In reality, it is not the integer value which is
added/subtracted, but rather the scale factor
times the value.
Ms. Surekha Mali
19 September 2022 Ms. Surekha Mali 23
Continue.....
Data Type Scale Factor
char 1
int 2
float 4
double 8
– If p1 is an integer pointer, then
p1++
will increment the value of p1 by 2.
19 September 2022 Ms. Surekha Mali 24
Example: to find the scale factors
#include <stdio.h>
main()
{
printf (“Number of bytes occupied by int is %d n”, sizeof(int));
printf (“Number of bytes occupied by float is %d n”, sizeof(float));
printf (“Number of bytes occupied by double is %d n”, sizeof(double));
printf (“Number of bytes occupied by char is %d n”, sizeof(char));
}
Output:
Number of bytes occupied by int is 2
Number of bytes occupied by float is 4
Number of bytes occupied by double is 8
Number of bytes occupied by char is 1
Returns no. of bytes required for data type representation
19 September 2022 Ms. Surekha Mali 25
Passing Pointers to a Function
• Pointers are often passed to a function as
arguments.
– Allows data items within the calling program to be
accessed by the function, altered, and then returned
to the calling program in altered form.
– Called call-by-reference (or by address or by
location).
• Normally, arguments are passed to a function
by value.
– The data items are copied to the function.
– Changes are not reflected in the calling program.
19 September 2022 Ms. Surekha Mali 26
Example: passing arguments by value
#include <stdio.h>
main()
{
int a, b;
a = 5 ; b = 20 ;
swap (a, b) ;
printf (“n a = %d, b = %d”, a, b);
}
void swap (int x, int y)
{
int t ;
t = x ;
x = y ;
y = t ;
}
Output
a = 5, b = 20
x and y swap
a and b
do not
swap
19 September 2022 Ms. Surekha Mali 27
Example: passing arguments by reference
#include <stdio.h>
main()
{
int a, b;
a = 5 ; b = 20 ;
swap (&a, &b) ;
printf (“n a = %d, b = %d”, a, b);
}
void swap (int *x, int *y)
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
}
Output
a = 20, b = 5
*x and *y
swap
*(&a) and *(&b)
swap
19 September 2022 Ms. Surekha Mali 28
scanf Revisited
int x, y ;
printf (“%d %d %d”, x, y, x+y) ;
• What about scanf ?
scanf (“%d %d %d”, x, y, x+y) ;
scanf (“%d %d”, &x, &y) ;
NO
YES
19 September 2022 Ms. Surekha Mali 29
Example: Sort 3 integers
• Three-step algorithm:
1. Read in three integers x, y and z
2. Put smallest in x
• Swap x, y if necessary; then swap x, z if necessary.
3. Put second smallest in y
• Swap y, z if necessary.
19 September 2022 Ms. Surekha Mali 30
Continue.....
#include <stdio.h>
main()
{
int x, y, z ;
………..
scanf (“%d %d %d”, &x, &y, &z) ;
if (x > y) swap (&x, &y);
if (x > z) swap (&x, &z);
if (y > z) swap (&y, &z) ;
………..
}
19 September 2022 Ms. Surekha Mali 31
sort3 as a function
#include <stdio.h>
main()
{
int x, y, z ;
………..
scanf (“%d %d %d”, &x, &y, &z) ;
sort3 (&x, &y, &z) ;
………..
}
void sort3 (int *xp, int *yp, int *zp)
{
if (*xp > *yp) swap (xp, yp);
if (*xp > *zp) swap (xp, zp);
if (*yp > *zp) swap (yp, zp);
}
xp/yp/zp
are
pointers
19 September 2022 Ms. Surekha Mali 32
Continue.....
• Why no ‘&’ in swap call?
– Because xp, yp and zp are already pointers that
point to the variables that we want to swap.
19 September 2022 Ms. Surekha Mali 33
Pointers and Arrays
• When an array is declared,
– The compiler allocates a base address and sufficient
amount of storage to contain all the elements of the
array in contiguous memory locations.
– The base address is the location of the first element
(index 0) of the array.
– The compiler also defines the array name as a
constant pointer to the first element.
19 September 2022 Ms. Surekha Mali 34
Example
• Consider the declaration:
int x[5] = {1, 2, 3, 4, 5} ;
– Suppose that the base address of x is 2500, and each
integer requires 4 bytes.
Element Value Address
x[0] 1 2500
x[1] 2 2504
x[2] 3 2508
x[3] 4 2512
x[4] 5 2516
19 September 2022 Ms. Surekha Mali 35
Continue.....
x  &x[0]  2500 ;
– p = x; and p = &x[0]; are equivalent.
– We can access successive values of x by using p++ or
p- - to move from one element to another.
• Relationship between p and x:
p = &x[0] = 2500
p+1 = &x[1] = 2504
p+2 = &x[2] = 2508
p+3 = &x[3] = 2512
p+4 = &x[4] = 2516
*(p+i) gives the
value of x[i]
19 September 2022 Ms. Surekha Mali 36
Continue.....
#include<stdio.h>
void main()
{
int a[3] = {1, 2, 3};
int *p = a;
for (int i = 0; i < 3; i++)
{
printf("%d", *p);
p++;
}
getch();
}
19 September 2022 Ms. Surekha Mali 37
Continue.....
#include <stdio.h>
int main() {
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i) {
// Equivalent to scanf("%d", &x[i]);
scanf("%d", x+i);
// Equivalent to sum += x[i]
sum += *(x+i);
}
printf("Sum = %d", sum);
return 0;
}
19 September 2022 Ms. Surekha Mali 38
Structures Revisited
• Recall that a structure can be declared as:
struct stud {
int roll;
char dept_code[25];
float cgpa;
};
struct stud a, b, c;
• And the individual structure elements can be
accessed as:
a.roll , b.roll , c.cgpa , etc.
19 September 2022 Ms. Surekha Mali 39
Arrays of Structures
• We can define an array of structure records as
struct stud class[100] ;
• The structure elements of the individual
records can be accessed as:
class[i].roll
class[20].dept_code
class[k++].cgpa
19 September 2022 Ms. Surekha Mali 40
Example: Sorting by Roll Numbers
#include <stdio.h>
struct stud
{
int roll;
char dept_code[25];
float cgpa;
};
main()
{
struc stud class[100], t;
int j, k, n;
scanf (“%d”, &n);
/* no. of students */
for (k=0; k<n; k++)
scanf (“%d %s %f”, &class[k].roll,
class[k].dept_code, &class[k].cgpa);
for (j=0; j<n-1; j++)
for (k=j+1; k<n; k++)
{
if (class[j].roll > class[k].roll)
{
t = class[j] ;
class[j] = class[k] ;
class[k] = t
}
}
<<<< PRINT THE RECORDS >>>>
}
19 September 2022 Ms. Surekha Mali 41
Pointers and Structures
• You may recall that the name of an array
stands for the address of its zero-th element.
– Also true for the names of arrays of structure
variables.
• Consider the declaration:
struct stud {
int roll;
char dept_code[25];
float cgpa;
} class[100], *ptr ;
19 September 2022 Ms. Surekha Mali 42
– The name class represents the address of the zero-th
element of the structure array.
– ptr is a pointer to data objects of the type struct stud.
• The assignment
ptr = class ;
will assign the address of class[0] to ptr.
• When the pointer ptr is incremented by one
(ptr++) :
– The value of ptr is actually increased by sizeof(stud).
– It is made to point to the next record.
19 September 2022 Ms. Surekha Mali 43
• Once ptr points to a structure variable, the
members can be accessed as:
ptr –> roll ;
ptr –> dept_code ;
ptr –> cgpa ;
– The symbol “–>” is called the arrow operator.
19 September 2022 Ms. Surekha Mali 44
1.#include <stdio.h>
2.#include <string.h>
3.struct student // create the Structure of student to store multiples items
4.{
5. char name[ 30];
6. int roll_no;
7. char state[100];
8. int age;
9.};
10.struct student s1, s2; // declare s1 and s2 variables of student structure
11.int main()
12.{
13. // records of the student s1
14. strcpy (s1.name, "John");
15. s1.roll_no = 1101;
16. strcpy (s1.state, "Los Angeles");
17. s1.age = 20;
19 September 2022 Ms. Surekha Mali 45
// records of the student s2
1. strcpy (s2.name, " Mark Douglas");
2. s2.roll_no = 111;
3. strcpy (s2.state, "California");
4. s2.age = 18;
5.
6. // print the details of the student s1;
7. printf (" Name of the student s1 is: %st ", s1.name);
8. printf (" n Roll No. of the student s1 is: %dt ", s1.roll_no);
9. printf (" n The state of the student s1 is: %st ", s1.state);
10. printf (" n Age of the student s1 is: %dt ", s1.age);
11.
12.
13. // print the details of the student s2;
14. printf ("n Name of the student s1 is: %st ", s2.name);
15. printf (" n Roll No. of the student s1 is: %dt ", s2.roll_no);
16. printf (" n The state of the student s1 is: %st ", s2.state);
17. printf (" n Age of the student s1 is: %dt ", s2.age);
18. return 0;
19.}
19 September 2022 Ms. Surekha Mali 46
Structure with Pointer Eg..
19 September 2022 Ms. Surekha Mali 47
48
1.#include <stdio.h>
2.
3.// create a structure Subject using the struct keyword
4.struct Subject
5.{
6. // declare the member of the Course structure
7. char sub_name[30];
8. int sub_id;
9. char sub_duration[50];
10. char sub_type[50];
11.};
12.
13.int main()
14.{
15. struct Subject sub; // declare the Subject variable
16. struct Subject *ptr; // create a pointer variable (*ptr)
17. ptr = ⊂ /* ptr variable pointing to the address of the structure variable sub
*/
Ms. Surekha Mali
49
1. strcpy (sub.sub_name, " Computer Science");
2. sub.sub_id = 1201;
3. strcpy (sub.sub_duration, "6 Months");
4. strcpy (sub.sub_type, " Multiple Choice Question");
5.// print the details of the Subject;
6. printf (" Subject Name: %st ", (*ptr).sub_name);
7. printf (" n Subject Id: %dt ", (*ptr).sub_id);
8. printf (" n Duration of the Subject: %st ", (*ptr).sub_duration);
9. printf (" n Type of the Subject: %st ", (*ptr).sub_type);
10.
11. return 0;
12.
13.}
Ms. Surekha Mali
50
Ms. Surekha Mali
19 September 2022 Ms. Surekha Mali 51
Example
#include <stdio.h>
typedef struct {
float real;
float imag;
} _COMPLEX;
swap_ref(_COMPLEX *a, _COMPLEX *b)
{
_COMPLEX tmp;
tmp=*a;
*a=*b;
*b=tmp;
}
print(_COMPLEX *a)
{
printf("(%f,%f)n",a->real,a->imag);
}
main()
{
_COMPLEX x={10.0,3.0}, y={-20.0,4.0};
print(&x); print(&y);
swap_ref(&x,&y);
print(&x); print(&y);
}
(10.000000,3.000000)
(-20.000000,4.000000)
(-20.000000,4.000000)
(10.000000,3.000000)
19 September 2022 Ms. Surekha Mali 52
A Warning
• When using structure pointers, we should take
care of operator precedence.
– Member operator “.” has higher precedence than “*”.
• ptr –> roll and (*ptr).roll mean the same thing.
• *ptr.roll will lead to error.
– The operator “–>” enjoys the highest priority among
operators.
• ++ptr –> roll will increment roll, not ptr.
• (++ptr) –> roll will do the intended thing.
19 September 2022 Ms. Surekha Mali 53
Structures and Functions
• A structure can be passed as argument to a
function.
• A function can also return a structure.
• The process shall be illustrated with the help of
an example.
– A function to add two complex numbers.
19 September 2022 Ms. Surekha Mali
54
Example:
#include <stdio.h>
struct student {
char name[50];
int age;
};
// function prototype
void display(struct student s);
int main() {
struct student s1;
printf("Enter name: ");
// read string input from the user until n is entered
// n is discarded
scanf("%[^n]%*c", s1.name);
19 September 2022 Ms. Surekha Mali 55
Example:
printf("Enter age: ");
scanf("%d", &s1.age);
display(s1); // passing struct as an argument
return 0;
}
void display(struct student s) {
printf("nDisplaying informationn");
printf("Name: %s", s.name);
printf("nAge: %d", s.age);
}
19 September 2022 Ms. Surekha Mali 56
Example:
19 September 2022 Ms. Surekha Mali 57
Example: Array Function and pointers
19 September 2022 Ms. Surekha Mali 58
1.#include <stdio.h>
2.float add(float,int);
3.float sub(float,int);
4.float mul(float,int);
5.float div(float,int);
6.int main()
7.{
8. float x; // variable declaration.
9. int y;
10. float (*fp[4]) (float,int); // function pointer declaration.
11. fp[0]=add; // assigning addresses to the elements of an array of a fu
nction pointer.
12. fp[1]=sub;
13. fp[2]=mul;
14. fp[3]=div;
15. printf("Enter the values of x and y :");
16. scanf("%f %d",&x,&y);
17. float r=(*fp[0]) (x,y); // Calling add() function.
18. float a=x+y;
19. return a;
20.}
19 September 2022 Ms. Surekha Mali 59
1. printf("nSum of two values is : %f",r);
2. r=(*fp[1]) (x,y); // Calling sub() funct
ion.
3. printf("nDifference of two values is : %f",r);
4. r=(*fp[2]) (x,y); // Calliung sub() fun
ction.
5. printf("nMultiplication of two values is : %f"
,r);
6. r=(*fp[3]) (x,y); // Calling div() functio
n.
7. printf("nDivision of two values is : %f",r);
8. return 0;
9.}
10.
11. float add(float x,int y)
12.{
13. float a=x+y;
14. return a;
15.}
1.float sub(float x,int y)
2.{
3. float a=x-y;
4. return a;
5.}
6.float mul(float x,int y)
7.{
8. float a=x*y;
9. return a;
10.}
11.float div(float x,int y)
12.{
13. float a=x/y;
14. return a;
15.}
19 September 2022 Ms. Surekha Mali 60
Dynamic Memory Allocation
19 September 2022 Ms. Surekha Mali 61
Basic Idea
• Many a time we face situations where data is
dynamic in nature.
– Amount of data cannot be predicted beforehand.
– Number of data item keeps changing during
program execution.
• Such situations can be handled more easily and
effectively using dynamic memory management
techniques.
19 September 2022 Ms. Surekha Mali 62
Continue.....
• C language requires the number of elements in
an array to be specified at compile time.
– Often leads to wastage or memory space or program
failure.
• Dynamic Memory Allocation
– Memory space required can be specified at the time
of execution.
– C supports allocating and freeing memory
dynamically using library routines.
19 September 2022 Ms. Surekha Mali 63
Memory Allocation Process in C
Local variables
Free memory
Global variables
Instructions
Permanent storage
area
Stack
Heap
19 September 2022 Ms. Surekha Mali 64
Continue.....
• The program instructions and the global
variables are stored in a region known as
permanent storage area.
• The local variables are stored in another area
called stack.
• The memory space between these two areas is
available for dynamic allocation during
execution of the program.
– This free region is called the heap.
– The size of the heap keeps changing
19 September 2022 Ms. Surekha Mali 65
Memory Allocation Functions
• malloc
– Allocates requested number of bytes and returns a
pointer to the first byte of the allocated space.
• calloc
– Allocates space for an array of elements, initializes
them to zero and then returns a pointer to the
memory.
• free
Frees previously allocated space.
• realloc
– Modifies the size of previously allocated space.
19 September 2022 Ms. Surekha Mali 66
Allocating a Block of Memory
• A block of memory can be allocated using the
function malloc.
– Reserves a block of memory of specified size and
returns a pointer of type void.
– The return pointer can be assigned to any pointer
type.
• General format:
ptr = (type *) malloc (byte_size) ;
19 September 2022 Ms. Surekha Mali 67
Continue.....
• Examples
p = (int *) malloc (100 * sizeof (int)) ;
• A memory space equivalent to “100 times the size of an int”
bytes is reserved.
• The address of the first byte of the allocated memory is
assigned to the pointer p of type int.
p
400 bytes of space
19 September 2022 Ms. Surekha Mali 68
Continue.....
cptr = (char *) malloc (20) ;
• Allocates 10 bytes of space for the pointer cptr of type char.
sptr = (struct stud *) malloc (10 *
sizeof (struct stud));
19 September 2022 Ms. Surekha Mali 69
Points to Note
• malloc always allocates a block of contiguous
bytes.
– The allocation can fail if sufficient contiguous
memory space is not available.
– If it fails, malloc returns NULL.
19 September 2022 Ms. Surekha Mali 70
Example
printf("Input heights for %d
students n",N);
for(i=0;i<N;i++)
scanf("%f",&height[i]);
for(i=0;i<N;i++)
sum+=height[i];
avg=sum/(float) N;
printf("Average height= %f n",
avg);
}
#include <stdio.h>
main()
{
int i,N;
float *height;
float sum=0,avg;
printf("Input the number of students. n");
scanf("%d",&N);
height=(float *) malloc(N * sizeof(float));
Input the number of
students.
5
Input heights for 5
students
23 24 25 26 27
Average height=
25.000000
19 September 2022 Ms. Surekha Mali 71
Releasing the Used Space
• When we no longer need the data stored in a
block of memory, we may release the block for
future use.
• How?
– By using the free function.
• General format:
free (ptr) ;
where ptr is a pointer to a memory block which
has been already created using malloc.
19 September 2022 Ms. Surekha Mali 72
Altering the Size of a Block
• Sometimes we need to alter the size of some
previously allocated memory block.
– More memory needed.
– Memory allocated is larger than necessary.
• How?
– By using the realloc function.
• If the original allocation is done by the statement
ptr = malloc (size) ;
then reallocation of space may be done as
ptr = realloc (ptr, newsize) ;
19 September 2022 Ms. Surekha Mali 73
Continue.....
– The new memory block may or may not begin at the
same place as the old one.
• If it does not find space, it will create it in an entirely
different region and move the contents of the old block into
the new block.
– The function guarantees that the old data remains
intact.
– If it is unable to allocate, it returns NULL and frees
the original block.
19 September 2022 Ms. Surekha Mali 74
Pointer to Pointer
• Example:
int **p;
p=(int **) malloc(3 * sizeof(int *));
p
p[2]
p[1]
p[0]
int *
int **
int *
int *
19 September 2022 Ms. Surekha Mali 75
2-D Array Allocation
#include <stdio.h>
#include <stdlib.h>
int **allocate(int h, int w)
{
int **p;
int i,j;
p=(int **) calloc(h, sizeof (int *) );
for(i=0;i<h;i++)
p[i]=(int *) calloc(w,sizeof (int));
return(p);
}
void read_data(int **p,int h,int w)
{
int i,j;
for(i=0;i<h;i++)
for(j=0;j<w;j++)
scanf ("%d",&p[i][j]);
}
Allocate array
of pointers
Allocate array of
integers for each
row
Elements accessed
like 2-D array elements.
19 September 2022 Ms. Surekha Mali 76
void print_data(int **p,int h,int w)
{
int i,j;
for(i=0;i<h;i++)
{
for(j=0;j<w;j++)
printf("%5d ",p[i][j]);
printf("n");
}
}
2-D Array: Continue.....
main()
{
int **p;
int M,N;
printf("Give M and N n");
scanf("%d%d",&M,&N);
p=allocate(M,N);
read_data(p,M,N);
printf("n The array read as n");
print_data(p,M,N);
}
Give M and
N
3 3
1 2 3
4 5 6
7 8 9
The array
read as
1 2 3
4 5 6
7 8 9
19 September 2022 Ms. Surekha Mali 77
Linked List :: Basic Concepts
• A list refers to a set of items organized
sequentially.
– An array is an example of a list.
• The array index is used for accessing and manipulation of
array elements.
– Problems with array:
• The array size has to be specified at the beginning.
• Deleting an element or inserting an element may require
shifting of elements.
19 September 2022 Ms. Surekha Mali 78
Continue.....
• A completely different way to represent a list:
– Make each item in the list part of a structure.
– The structure also contains a pointer or link to the
structure containing the next item.
– This type of list is called a linked list.
Structure 1
item
Structure 2
item
Structure 3
item
19 September 2022 Ms. Surekha Mali 79
Continue.....
• Each structure of the list is called a node, and
consists of two fields:
– One containing the item.
– The other containing the address of the next item in
the list.
• The data items comprising a linked list need
not be contiguous in memory.
– They are ordered by logical links that are stored as
part of the data in the structure itself.
– The link is a pointer to another structure of the
same type.
19 September 2022 Ms. Surekha Mali 80
Continue.....
• Such a structure can be represented as:
struct node
{
int item;
struct node *next;
} ;
• Such structures which contain a member field
pointing to the same structure type are called
self-referential structures.
item
node
next
19 September 2022 Ms. Surekha Mali 81
Continue.....
• In general, a node may be represented as
follows:
struct node_name
{
type member1;
type member2;
………
struct node_name *next;
};
19 September 2022 Ms. Surekha Mali 82
Illustration
• Consider the structure:
struct stud
{
int roll;
char name[30];
int age;
struct stud *next;
};
• Also assume that the list consists of three nodes
n1, n2 and n3.
struct stud n1, n2, n3;
19 September 2022 Ms. Surekha Mali 83
Continue.....
• To create the links between nodes, we can
write:
n1.next = &n2 ;
n2.next = &n3 ;
n3.next = NULL ; /* No more nodes follow */
• Now the list looks like:
n1 n2 n3
roll
name
age
next
19 September 2022 Ms. Surekha Mali 84
Example
#include <stdio.h>
struct stud
{
int roll;
char name[30];
int age;
struct stud *next;
};
main()
{
struct stud n1, n2, n3;
struct stud *p;
scanf (“%d %s %d”, &n1.roll,
n1.name, &n1.age);
scanf (“%d %s %d”, &n2.roll,
n2.name, &n2.age);
scanf (“%d %s %d”, &n3.roll,
n3.name, &n3.age);
n1.next = &n2 ;
n2.next = &n3 ;
n3.next = NULL ;
/* Now traverse the list and print
the elements */
p = n1 ; /* point to 1st element */
while (p != NULL)
{
printf (“n %d %s %d”,
p->roll, p->name, p->age);
p = p->next;
}
}
Thank you
19 September 2022 Ms. Surekha Mali 85

More Related Content

Similar to pointers CP Lecture.ppt

All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
GkhanGirgin3
 

Similar to pointers CP Lecture.ppt (20)

C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Engineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptxEngineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptx
 
Basics of C programming - day 2
Basics of C programming - day 2Basics of C programming - day 2
Basics of C programming - day 2
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
Code optimization
Code optimization Code optimization
Code optimization
 
Code optimization
Code optimization Code optimization
Code optimization
 
pointers 1
pointers 1pointers 1
pointers 1
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
 
9.C Programming
9.C Programming9.C Programming
9.C Programming
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
chapter-7 slide.pptx
chapter-7 slide.pptxchapter-7 slide.pptx
chapter-7 slide.pptx
 
Functions
FunctionsFunctions
Functions
 
C lab programs
C lab programsC lab programs
C lab programs
 
C lab programs
C lab programsC lab programs
C lab programs
 
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Recently uploaded (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 

pointers CP Lecture.ppt

  • 2. 19 September 2022 2 Introduction • A pointer is a variable that represents the location (rather than the value) of a data item. • They have a number of useful applications. – Enables us to access a variable that is defined outside the function. – Can be used to pass information back and forth between a function and its reference point. – More efficient in handling data tables. – Reduces the length and complexity of a program. – Sometimes also increases the execution speed. Ms. Surekha Mali
  • 3. 19 September 2022 3 Basic Concept • Within the computer memory, every stored data item occupies one or more contiguous memory cells. – The number of memory cells required to store a data item depends on its type (char, int, double, etc.). • Whenever we declare a variable, the system allocates memory location(s) to hold the value of the variable. – Since every byte in memory has a unique address, this location will also have its own (unique) address. Ms. Surekha Mali
  • 4. 19 September 2022 4 Continue.....Example Ms. Surekha Mali Int *p , number; P=&number;
  • 5. 19 September 2022 5 Continue..... • Consider the statement int xyz = 50; – This statement instructs the compiler to allocate a location for the integer variable xyz, and put the value 50 in that location. – Suppose that the address location chosen is 1380. xyz  variable 50  value 1380  address Ms. Surekha Mali
  • 6. 19 September 2022 Ms. Surekha Mali 6 Continue..... • During execution of the program, the system always associates the name xyz with the address 1380. – The value 50 can be accessed by using either the name xyz or the address 1380. • Since memory addresses are simply numbers, they can be assigned to some variables which can be stored in memory. – Such variables that hold memory addresses are called pointers. – Since a pointer is a variable, its value is also stored in some memory location.
  • 7. 19 September 2022 Ms. Surekha Mali 7 Continue..... • Suppose we assign the address of xyz to a variable p. – p is said to point to the variable xyz. Variable Value Address xyz 50 1380 p 1380 2545 p = &xyz; 50 1380 xyz 1380 2545 p
  • 8. 19 September 2022 Ms. Surekha Mali 8 Accessing the Address of a Variable • The address of a variable can be determined using the ‘&’ operator. – The operator ‘&’ immediately preceding a variable returns the address of the variable. • Example: p = &xyz; – The address of xyz (1380) is assigned to p. • The ‘&’ operator can be used only with a simple variable or an array element. &distance &x[0] &x[i-2]
  • 9. 19 September 2022 Ms. Surekha Mali 9 Continue..... • Following usages are illegal: &235 • Pointing at constant. int arr[20]; : &arr; • Pointing at array name. &(a+b) • Pointing at expression.
  • 10. 19 September 2022 Ms. Surekha Mali 10 Example #include <stdio.h> main() { int a; float b, c; double d; char ch; a = 10; b = 2.5; c = 12.36; d = 12345.66; ch = ‘A’; printf (“%d is stored in location %u n”, a, &a) ; printf (“%f is stored in location %u n”, b, &b) ; printf (“%f is stored in location %u n”, c, &c) ; printf (“%ld is stored in location %u n”, d, &d) ; printf (“%c is stored in location %u n”, ch, &ch) ; }
  • 11. 19 September 2022 Ms. Surekha Mali 11 Output: 10 is stored in location 3221224908 2.500000 is stored in location 3221224904 12.360000 is stored in location 3221224900 12345.660000 is stored in location 3221224892 A is stored in location 3221224891 Incidentally variables a,b,c,d and ch are allocated to contiguous memory locations. a b c d ch
  • 12. 19 September 2022 Ms. Surekha Mali 12 Pointer Declarations • Pointer variables must be declared before we use them. • General form: data_type *pointer_name; Three things are specified in the above declaration: 1. The asterisk (*) tells that the variable pointer_name is a pointer variable. 2. pointer_name needs a memory location. 3. pointer_name points to a variable of type data_type.
  • 13. 19 September 2022 Ms. Surekha Mali 13 Continue..... • Example: int *count; float *speed; • Once a pointer variable has been declared, it can be made to point to a variable using an assignment statement like: int *p, xyz; : p = &xyz; – This is called pointer initialization.
  • 14. 19 September 2022 Ms. Surekha Mali 14 Things to Remember • Pointer variables must always point to a data item of the same type. float x; int *p; :  will result in erroneous output p = &x; • Assigning an absolute address to a pointer variable is prohibited. int *count; : count = 1268;
  • 15. 19 September 2022 Ms. Surekha Mali 15 Accessing a Variable Through its Pointer • Once a pointer has been assigned the address of a variable, the value of the variable can be accessed using the indirection operator (*). int a, b; int *p; : p = &a; b = *p; Equivalent to b = a
  • 16. 19 September 2022 Ms. Surekha Mali 16 Example 1 #include <stdio.h> main() { int a, b; int c = 5; int *p; a = 4 * (c + 5) ; p = &c; b = 4 * (*p + 5) ; printf (“a=%d b=%d n”, a, b) ; } Equivalent
  • 17. 19 September 2022 Ms. Surekha Mali 17 Example 2 #include <stdio.h> main() { int x, y; int *ptr; x = 10 ; ptr = &x ; y = *ptr ; printf (“%d is stored in location %u n”, x, &x) ; printf (“%d is stored in location %u n”, *&x, &x) ; printf (“%d is stored in location %u n”, *ptr, ptr) ; printf (“%d is stored in location %u n”, y, &*ptr) ; printf (“%u is stored in location %u n”, ptr, &ptr) ; printf (“%d is stored in location %u n”, y, &y) ; *ptr = 25; printf (“nNow x = %d n”, x); } *&xx ptr=&x; &x&*ptr
  • 18. 19 September 2022 Ms. Surekha Mali 18 Output: 10 is stored in location 3221224908 10 is stored in location 3221224908 10 is stored in location 3221224908 10 is stored in location 3221224908 3221224908 is stored in location 3221224900 10 is stored in location 3221224904 Now x = 25 Address of x: 3221224908 Address of y: 3221224904 Address of ptr: 3221224900
  • 19. 19 September 2022 Ms. Surekha Mali 19 1.#include<stdio.h> 2.int main(){ 3.int number=50; 4.int *p; 5.p=&number;//stores the address of number variable 6.printf("Address of p variable is %x n",p); // p contains the address of the nu mber therefore printing p gives the address of number. 7.printf("Value of p variable is %d n",*p); // As we know that * is used to deref erence a pointer therefore if we print *p, we will get the value stored at the ad dress contained by p. 8.return 0; 9.} Example 3
  • 20. 19 September 2022 Ms. Surekha Mali 20 Pointer Expressions • Like other variables, pointer variables can be used in expressions. • If p1 and p2 are two pointers, the following statements are valid: sum = *p1 + *p2 ; prod = *p1 * *p2 ; prod = (*p1) * (*p2) ; *p1 = *p1 + 2; x = *p1 / *p2 + 5 ;
  • 21. 19 September 2022 Ms. Surekha Mali 21 Continue..... • What are allowed in C? – Add an integer to a pointer. – Subtract an integer from a pointer. – Subtract one pointer from another (related). • If p1 and p2 are both pointers to the same array, them p2–p1 gives the number of elements between p1 and p2. • What are not allowed? – Add two pointers. p1 = p1 + p2 ; – Multiply / divide a pointer in an expression. p1 = p2 / 5 ; p1 = p1 – p2 * 10 ;
  • 22. 19 September 2022 22 Scale Factor • We have seen that an integer value can be added to or subtracted from a pointer variable. int *p1, *p2 ; int i, j; : p1 = p1 + 1 ; p2 = p1 + j ; p2++ ; p2 = p2 – (i + j) ; • In reality, it is not the integer value which is added/subtracted, but rather the scale factor times the value. Ms. Surekha Mali
  • 23. 19 September 2022 Ms. Surekha Mali 23 Continue..... Data Type Scale Factor char 1 int 2 float 4 double 8 – If p1 is an integer pointer, then p1++ will increment the value of p1 by 2.
  • 24. 19 September 2022 Ms. Surekha Mali 24 Example: to find the scale factors #include <stdio.h> main() { printf (“Number of bytes occupied by int is %d n”, sizeof(int)); printf (“Number of bytes occupied by float is %d n”, sizeof(float)); printf (“Number of bytes occupied by double is %d n”, sizeof(double)); printf (“Number of bytes occupied by char is %d n”, sizeof(char)); } Output: Number of bytes occupied by int is 2 Number of bytes occupied by float is 4 Number of bytes occupied by double is 8 Number of bytes occupied by char is 1 Returns no. of bytes required for data type representation
  • 25. 19 September 2022 Ms. Surekha Mali 25 Passing Pointers to a Function • Pointers are often passed to a function as arguments. – Allows data items within the calling program to be accessed by the function, altered, and then returned to the calling program in altered form. – Called call-by-reference (or by address or by location). • Normally, arguments are passed to a function by value. – The data items are copied to the function. – Changes are not reflected in the calling program.
  • 26. 19 September 2022 Ms. Surekha Mali 26 Example: passing arguments by value #include <stdio.h> main() { int a, b; a = 5 ; b = 20 ; swap (a, b) ; printf (“n a = %d, b = %d”, a, b); } void swap (int x, int y) { int t ; t = x ; x = y ; y = t ; } Output a = 5, b = 20 x and y swap a and b do not swap
  • 27. 19 September 2022 Ms. Surekha Mali 27 Example: passing arguments by reference #include <stdio.h> main() { int a, b; a = 5 ; b = 20 ; swap (&a, &b) ; printf (“n a = %d, b = %d”, a, b); } void swap (int *x, int *y) { int t ; t = *x ; *x = *y ; *y = t ; } Output a = 20, b = 5 *x and *y swap *(&a) and *(&b) swap
  • 28. 19 September 2022 Ms. Surekha Mali 28 scanf Revisited int x, y ; printf (“%d %d %d”, x, y, x+y) ; • What about scanf ? scanf (“%d %d %d”, x, y, x+y) ; scanf (“%d %d”, &x, &y) ; NO YES
  • 29. 19 September 2022 Ms. Surekha Mali 29 Example: Sort 3 integers • Three-step algorithm: 1. Read in three integers x, y and z 2. Put smallest in x • Swap x, y if necessary; then swap x, z if necessary. 3. Put second smallest in y • Swap y, z if necessary.
  • 30. 19 September 2022 Ms. Surekha Mali 30 Continue..... #include <stdio.h> main() { int x, y, z ; ……….. scanf (“%d %d %d”, &x, &y, &z) ; if (x > y) swap (&x, &y); if (x > z) swap (&x, &z); if (y > z) swap (&y, &z) ; ……….. }
  • 31. 19 September 2022 Ms. Surekha Mali 31 sort3 as a function #include <stdio.h> main() { int x, y, z ; ……….. scanf (“%d %d %d”, &x, &y, &z) ; sort3 (&x, &y, &z) ; ……….. } void sort3 (int *xp, int *yp, int *zp) { if (*xp > *yp) swap (xp, yp); if (*xp > *zp) swap (xp, zp); if (*yp > *zp) swap (yp, zp); } xp/yp/zp are pointers
  • 32. 19 September 2022 Ms. Surekha Mali 32 Continue..... • Why no ‘&’ in swap call? – Because xp, yp and zp are already pointers that point to the variables that we want to swap.
  • 33. 19 September 2022 Ms. Surekha Mali 33 Pointers and Arrays • When an array is declared, – The compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. – The base address is the location of the first element (index 0) of the array. – The compiler also defines the array name as a constant pointer to the first element.
  • 34. 19 September 2022 Ms. Surekha Mali 34 Example • Consider the declaration: int x[5] = {1, 2, 3, 4, 5} ; – Suppose that the base address of x is 2500, and each integer requires 4 bytes. Element Value Address x[0] 1 2500 x[1] 2 2504 x[2] 3 2508 x[3] 4 2512 x[4] 5 2516
  • 35. 19 September 2022 Ms. Surekha Mali 35 Continue..... x  &x[0]  2500 ; – p = x; and p = &x[0]; are equivalent. – We can access successive values of x by using p++ or p- - to move from one element to another. • Relationship between p and x: p = &x[0] = 2500 p+1 = &x[1] = 2504 p+2 = &x[2] = 2508 p+3 = &x[3] = 2512 p+4 = &x[4] = 2516 *(p+i) gives the value of x[i]
  • 36. 19 September 2022 Ms. Surekha Mali 36 Continue..... #include<stdio.h> void main() { int a[3] = {1, 2, 3}; int *p = a; for (int i = 0; i < 3; i++) { printf("%d", *p); p++; } getch(); }
  • 37. 19 September 2022 Ms. Surekha Mali 37 Continue..... #include <stdio.h> int main() { int i, x[6], sum = 0; printf("Enter 6 numbers: "); for(i = 0; i < 6; ++i) { // Equivalent to scanf("%d", &x[i]); scanf("%d", x+i); // Equivalent to sum += x[i] sum += *(x+i); } printf("Sum = %d", sum); return 0; }
  • 38. 19 September 2022 Ms. Surekha Mali 38 Structures Revisited • Recall that a structure can be declared as: struct stud { int roll; char dept_code[25]; float cgpa; }; struct stud a, b, c; • And the individual structure elements can be accessed as: a.roll , b.roll , c.cgpa , etc.
  • 39. 19 September 2022 Ms. Surekha Mali 39 Arrays of Structures • We can define an array of structure records as struct stud class[100] ; • The structure elements of the individual records can be accessed as: class[i].roll class[20].dept_code class[k++].cgpa
  • 40. 19 September 2022 Ms. Surekha Mali 40 Example: Sorting by Roll Numbers #include <stdio.h> struct stud { int roll; char dept_code[25]; float cgpa; }; main() { struc stud class[100], t; int j, k, n; scanf (“%d”, &n); /* no. of students */ for (k=0; k<n; k++) scanf (“%d %s %f”, &class[k].roll, class[k].dept_code, &class[k].cgpa); for (j=0; j<n-1; j++) for (k=j+1; k<n; k++) { if (class[j].roll > class[k].roll) { t = class[j] ; class[j] = class[k] ; class[k] = t } } <<<< PRINT THE RECORDS >>>> }
  • 41. 19 September 2022 Ms. Surekha Mali 41 Pointers and Structures • You may recall that the name of an array stands for the address of its zero-th element. – Also true for the names of arrays of structure variables. • Consider the declaration: struct stud { int roll; char dept_code[25]; float cgpa; } class[100], *ptr ;
  • 42. 19 September 2022 Ms. Surekha Mali 42 – The name class represents the address of the zero-th element of the structure array. – ptr is a pointer to data objects of the type struct stud. • The assignment ptr = class ; will assign the address of class[0] to ptr. • When the pointer ptr is incremented by one (ptr++) : – The value of ptr is actually increased by sizeof(stud). – It is made to point to the next record.
  • 43. 19 September 2022 Ms. Surekha Mali 43 • Once ptr points to a structure variable, the members can be accessed as: ptr –> roll ; ptr –> dept_code ; ptr –> cgpa ; – The symbol “–>” is called the arrow operator.
  • 44. 19 September 2022 Ms. Surekha Mali 44 1.#include <stdio.h> 2.#include <string.h> 3.struct student // create the Structure of student to store multiples items 4.{ 5. char name[ 30]; 6. int roll_no; 7. char state[100]; 8. int age; 9.}; 10.struct student s1, s2; // declare s1 and s2 variables of student structure 11.int main() 12.{ 13. // records of the student s1 14. strcpy (s1.name, "John"); 15. s1.roll_no = 1101; 16. strcpy (s1.state, "Los Angeles"); 17. s1.age = 20;
  • 45. 19 September 2022 Ms. Surekha Mali 45 // records of the student s2 1. strcpy (s2.name, " Mark Douglas"); 2. s2.roll_no = 111; 3. strcpy (s2.state, "California"); 4. s2.age = 18; 5. 6. // print the details of the student s1; 7. printf (" Name of the student s1 is: %st ", s1.name); 8. printf (" n Roll No. of the student s1 is: %dt ", s1.roll_no); 9. printf (" n The state of the student s1 is: %st ", s1.state); 10. printf (" n Age of the student s1 is: %dt ", s1.age); 11. 12. 13. // print the details of the student s2; 14. printf ("n Name of the student s1 is: %st ", s2.name); 15. printf (" n Roll No. of the student s1 is: %dt ", s2.roll_no); 16. printf (" n The state of the student s1 is: %st ", s2.state); 17. printf (" n Age of the student s1 is: %dt ", s2.age); 18. return 0; 19.}
  • 46. 19 September 2022 Ms. Surekha Mali 46
  • 47. Structure with Pointer Eg.. 19 September 2022 Ms. Surekha Mali 47
  • 48. 48 1.#include <stdio.h> 2. 3.// create a structure Subject using the struct keyword 4.struct Subject 5.{ 6. // declare the member of the Course structure 7. char sub_name[30]; 8. int sub_id; 9. char sub_duration[50]; 10. char sub_type[50]; 11.}; 12. 13.int main() 14.{ 15. struct Subject sub; // declare the Subject variable 16. struct Subject *ptr; // create a pointer variable (*ptr) 17. ptr = ⊂ /* ptr variable pointing to the address of the structure variable sub */ Ms. Surekha Mali
  • 49. 49 1. strcpy (sub.sub_name, " Computer Science"); 2. sub.sub_id = 1201; 3. strcpy (sub.sub_duration, "6 Months"); 4. strcpy (sub.sub_type, " Multiple Choice Question"); 5.// print the details of the Subject; 6. printf (" Subject Name: %st ", (*ptr).sub_name); 7. printf (" n Subject Id: %dt ", (*ptr).sub_id); 8. printf (" n Duration of the Subject: %st ", (*ptr).sub_duration); 9. printf (" n Type of the Subject: %st ", (*ptr).sub_type); 10. 11. return 0; 12. 13.} Ms. Surekha Mali
  • 51. 19 September 2022 Ms. Surekha Mali 51 Example #include <stdio.h> typedef struct { float real; float imag; } _COMPLEX; swap_ref(_COMPLEX *a, _COMPLEX *b) { _COMPLEX tmp; tmp=*a; *a=*b; *b=tmp; } print(_COMPLEX *a) { printf("(%f,%f)n",a->real,a->imag); } main() { _COMPLEX x={10.0,3.0}, y={-20.0,4.0}; print(&x); print(&y); swap_ref(&x,&y); print(&x); print(&y); } (10.000000,3.000000) (-20.000000,4.000000) (-20.000000,4.000000) (10.000000,3.000000)
  • 52. 19 September 2022 Ms. Surekha Mali 52 A Warning • When using structure pointers, we should take care of operator precedence. – Member operator “.” has higher precedence than “*”. • ptr –> roll and (*ptr).roll mean the same thing. • *ptr.roll will lead to error. – The operator “–>” enjoys the highest priority among operators. • ++ptr –> roll will increment roll, not ptr. • (++ptr) –> roll will do the intended thing.
  • 53. 19 September 2022 Ms. Surekha Mali 53 Structures and Functions • A structure can be passed as argument to a function. • A function can also return a structure. • The process shall be illustrated with the help of an example. – A function to add two complex numbers.
  • 54. 19 September 2022 Ms. Surekha Mali 54 Example: #include <stdio.h> struct student { char name[50]; int age; }; // function prototype void display(struct student s); int main() { struct student s1; printf("Enter name: "); // read string input from the user until n is entered // n is discarded scanf("%[^n]%*c", s1.name);
  • 55. 19 September 2022 Ms. Surekha Mali 55 Example: printf("Enter age: "); scanf("%d", &s1.age); display(s1); // passing struct as an argument return 0; } void display(struct student s) { printf("nDisplaying informationn"); printf("Name: %s", s.name); printf("nAge: %d", s.age); }
  • 56. 19 September 2022 Ms. Surekha Mali 56 Example:
  • 57. 19 September 2022 Ms. Surekha Mali 57 Example: Array Function and pointers
  • 58. 19 September 2022 Ms. Surekha Mali 58 1.#include <stdio.h> 2.float add(float,int); 3.float sub(float,int); 4.float mul(float,int); 5.float div(float,int); 6.int main() 7.{ 8. float x; // variable declaration. 9. int y; 10. float (*fp[4]) (float,int); // function pointer declaration. 11. fp[0]=add; // assigning addresses to the elements of an array of a fu nction pointer. 12. fp[1]=sub; 13. fp[2]=mul; 14. fp[3]=div; 15. printf("Enter the values of x and y :"); 16. scanf("%f %d",&x,&y); 17. float r=(*fp[0]) (x,y); // Calling add() function. 18. float a=x+y; 19. return a; 20.}
  • 59. 19 September 2022 Ms. Surekha Mali 59 1. printf("nSum of two values is : %f",r); 2. r=(*fp[1]) (x,y); // Calling sub() funct ion. 3. printf("nDifference of two values is : %f",r); 4. r=(*fp[2]) (x,y); // Calliung sub() fun ction. 5. printf("nMultiplication of two values is : %f" ,r); 6. r=(*fp[3]) (x,y); // Calling div() functio n. 7. printf("nDivision of two values is : %f",r); 8. return 0; 9.} 10. 11. float add(float x,int y) 12.{ 13. float a=x+y; 14. return a; 15.} 1.float sub(float x,int y) 2.{ 3. float a=x-y; 4. return a; 5.} 6.float mul(float x,int y) 7.{ 8. float a=x*y; 9. return a; 10.} 11.float div(float x,int y) 12.{ 13. float a=x/y; 14. return a; 15.}
  • 60. 19 September 2022 Ms. Surekha Mali 60 Dynamic Memory Allocation
  • 61. 19 September 2022 Ms. Surekha Mali 61 Basic Idea • Many a time we face situations where data is dynamic in nature. – Amount of data cannot be predicted beforehand. – Number of data item keeps changing during program execution. • Such situations can be handled more easily and effectively using dynamic memory management techniques.
  • 62. 19 September 2022 Ms. Surekha Mali 62 Continue..... • C language requires the number of elements in an array to be specified at compile time. – Often leads to wastage or memory space or program failure. • Dynamic Memory Allocation – Memory space required can be specified at the time of execution. – C supports allocating and freeing memory dynamically using library routines.
  • 63. 19 September 2022 Ms. Surekha Mali 63 Memory Allocation Process in C Local variables Free memory Global variables Instructions Permanent storage area Stack Heap
  • 64. 19 September 2022 Ms. Surekha Mali 64 Continue..... • The program instructions and the global variables are stored in a region known as permanent storage area. • The local variables are stored in another area called stack. • The memory space between these two areas is available for dynamic allocation during execution of the program. – This free region is called the heap. – The size of the heap keeps changing
  • 65. 19 September 2022 Ms. Surekha Mali 65 Memory Allocation Functions • malloc – Allocates requested number of bytes and returns a pointer to the first byte of the allocated space. • calloc – Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. • free Frees previously allocated space. • realloc – Modifies the size of previously allocated space.
  • 66. 19 September 2022 Ms. Surekha Mali 66 Allocating a Block of Memory • A block of memory can be allocated using the function malloc. – Reserves a block of memory of specified size and returns a pointer of type void. – The return pointer can be assigned to any pointer type. • General format: ptr = (type *) malloc (byte_size) ;
  • 67. 19 September 2022 Ms. Surekha Mali 67 Continue..... • Examples p = (int *) malloc (100 * sizeof (int)) ; • A memory space equivalent to “100 times the size of an int” bytes is reserved. • The address of the first byte of the allocated memory is assigned to the pointer p of type int. p 400 bytes of space
  • 68. 19 September 2022 Ms. Surekha Mali 68 Continue..... cptr = (char *) malloc (20) ; • Allocates 10 bytes of space for the pointer cptr of type char. sptr = (struct stud *) malloc (10 * sizeof (struct stud));
  • 69. 19 September 2022 Ms. Surekha Mali 69 Points to Note • malloc always allocates a block of contiguous bytes. – The allocation can fail if sufficient contiguous memory space is not available. – If it fails, malloc returns NULL.
  • 70. 19 September 2022 Ms. Surekha Mali 70 Example printf("Input heights for %d students n",N); for(i=0;i<N;i++) scanf("%f",&height[i]); for(i=0;i<N;i++) sum+=height[i]; avg=sum/(float) N; printf("Average height= %f n", avg); } #include <stdio.h> main() { int i,N; float *height; float sum=0,avg; printf("Input the number of students. n"); scanf("%d",&N); height=(float *) malloc(N * sizeof(float)); Input the number of students. 5 Input heights for 5 students 23 24 25 26 27 Average height= 25.000000
  • 71. 19 September 2022 Ms. Surekha Mali 71 Releasing the Used Space • When we no longer need the data stored in a block of memory, we may release the block for future use. • How? – By using the free function. • General format: free (ptr) ; where ptr is a pointer to a memory block which has been already created using malloc.
  • 72. 19 September 2022 Ms. Surekha Mali 72 Altering the Size of a Block • Sometimes we need to alter the size of some previously allocated memory block. – More memory needed. – Memory allocated is larger than necessary. • How? – By using the realloc function. • If the original allocation is done by the statement ptr = malloc (size) ; then reallocation of space may be done as ptr = realloc (ptr, newsize) ;
  • 73. 19 September 2022 Ms. Surekha Mali 73 Continue..... – The new memory block may or may not begin at the same place as the old one. • If it does not find space, it will create it in an entirely different region and move the contents of the old block into the new block. – The function guarantees that the old data remains intact. – If it is unable to allocate, it returns NULL and frees the original block.
  • 74. 19 September 2022 Ms. Surekha Mali 74 Pointer to Pointer • Example: int **p; p=(int **) malloc(3 * sizeof(int *)); p p[2] p[1] p[0] int * int ** int * int *
  • 75. 19 September 2022 Ms. Surekha Mali 75 2-D Array Allocation #include <stdio.h> #include <stdlib.h> int **allocate(int h, int w) { int **p; int i,j; p=(int **) calloc(h, sizeof (int *) ); for(i=0;i<h;i++) p[i]=(int *) calloc(w,sizeof (int)); return(p); } void read_data(int **p,int h,int w) { int i,j; for(i=0;i<h;i++) for(j=0;j<w;j++) scanf ("%d",&p[i][j]); } Allocate array of pointers Allocate array of integers for each row Elements accessed like 2-D array elements.
  • 76. 19 September 2022 Ms. Surekha Mali 76 void print_data(int **p,int h,int w) { int i,j; for(i=0;i<h;i++) { for(j=0;j<w;j++) printf("%5d ",p[i][j]); printf("n"); } } 2-D Array: Continue..... main() { int **p; int M,N; printf("Give M and N n"); scanf("%d%d",&M,&N); p=allocate(M,N); read_data(p,M,N); printf("n The array read as n"); print_data(p,M,N); } Give M and N 3 3 1 2 3 4 5 6 7 8 9 The array read as 1 2 3 4 5 6 7 8 9
  • 77. 19 September 2022 Ms. Surekha Mali 77 Linked List :: Basic Concepts • A list refers to a set of items organized sequentially. – An array is an example of a list. • The array index is used for accessing and manipulation of array elements. – Problems with array: • The array size has to be specified at the beginning. • Deleting an element or inserting an element may require shifting of elements.
  • 78. 19 September 2022 Ms. Surekha Mali 78 Continue..... • A completely different way to represent a list: – Make each item in the list part of a structure. – The structure also contains a pointer or link to the structure containing the next item. – This type of list is called a linked list. Structure 1 item Structure 2 item Structure 3 item
  • 79. 19 September 2022 Ms. Surekha Mali 79 Continue..... • Each structure of the list is called a node, and consists of two fields: – One containing the item. – The other containing the address of the next item in the list. • The data items comprising a linked list need not be contiguous in memory. – They are ordered by logical links that are stored as part of the data in the structure itself. – The link is a pointer to another structure of the same type.
  • 80. 19 September 2022 Ms. Surekha Mali 80 Continue..... • Such a structure can be represented as: struct node { int item; struct node *next; } ; • Such structures which contain a member field pointing to the same structure type are called self-referential structures. item node next
  • 81. 19 September 2022 Ms. Surekha Mali 81 Continue..... • In general, a node may be represented as follows: struct node_name { type member1; type member2; ……… struct node_name *next; };
  • 82. 19 September 2022 Ms. Surekha Mali 82 Illustration • Consider the structure: struct stud { int roll; char name[30]; int age; struct stud *next; }; • Also assume that the list consists of three nodes n1, n2 and n3. struct stud n1, n2, n3;
  • 83. 19 September 2022 Ms. Surekha Mali 83 Continue..... • To create the links between nodes, we can write: n1.next = &n2 ; n2.next = &n3 ; n3.next = NULL ; /* No more nodes follow */ • Now the list looks like: n1 n2 n3 roll name age next
  • 84. 19 September 2022 Ms. Surekha Mali 84 Example #include <stdio.h> struct stud { int roll; char name[30]; int age; struct stud *next; }; main() { struct stud n1, n2, n3; struct stud *p; scanf (“%d %s %d”, &n1.roll, n1.name, &n1.age); scanf (“%d %s %d”, &n2.roll, n2.name, &n2.age); scanf (“%d %s %d”, &n3.roll, n3.name, &n3.age); n1.next = &n2 ; n2.next = &n3 ; n3.next = NULL ; /* Now traverse the list and print the elements */ p = n1 ; /* point to 1st element */ while (p != NULL) { printf (“n %d %s %d”, p->roll, p->name, p->age); p = p->next; } }
  • 85. Thank you 19 September 2022 Ms. Surekha Mali 85