Pointers in C
Pointers in C
November 6, 2024 1
Introduction
November 6, 2024 2
Basic Concept
November 6, 2024 3
Contd.
xyz variable
50 value
1380 address
November 6, 2024 4
Contd.
• 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.
November 6, 2024 5
Contd.
int arr[20];
:
&arr;
• Pointing at array name.
&(a+b)
• Pointing at expression.
November 6, 2024 8
Example
#include <stdio.h>
main()
{
int a;
float b, c;
double d;
char ch;
November 6, 2024 9
Output:
November 6, 2024 10
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.
November 6, 2024 11
Contd.
• 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.
November 6, 2024 12
Things to Remember
November 6, 2024 14
Example 1
#include <stdio.h>
main()
{
int a, b;
int c = 5; Equivalent
int *p;
a = 4 * (c + 5) ;
p = &c;
b = 4 * (*p + 5) ;
printf (“a=%d b=%d \n”, a, b) ;
}
November 6, 2024 15
Example 2
#include <stdio.h>
main()
{
int x, y; *&xx
int *ptr;
x = 10 ;
ptr=&x;
ptr = &x ; &x&*ptr
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);
}
November 6, 2024 16
Output: Address of x: 3221224908
Address of y: 3221224904
Now x = 25
November 6, 2024 17
Pointer Expressions
November 6, 2024 18
Contd.
• 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 ;
November 6, 2024 19
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.
November 6, 2024 20
Contd.
November 6, 2024 21
Example:
Returns torequired
no. of bytes find theforscale factors
data type representation
#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:
November 6, 2024 22
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.
November 6, 2024 23
Example: passing arguments by value
#include <stdio.h>
main()
{ a and b
int a, b; do not
a = 5 ; b = 20 ; swap
swap (a, b) ; Output
printf (“\n a = %d, b = %d”, a, b);
} a = 5, b = 20
}
}
}
November 6, 2024 26
Pointers and Arrays
November 6, 2024 27
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
November 6, 2024 28
Contd.
x &x[0] 2500 ;
November 6, 2024 29
Example: function to find average
int *array
#include <stdio.h> float avg (int array[ ],int size)
main() {
{ int *p, i , sum = 0;
int x[100], k, n ;
p = array ; p[i]
scanf (“%d”, &n) ;
for (i=0; i<size; i++)
for (k=0; k<n; k++) sum = sum + *(p+i);
scanf (“%d”, &x[k]) ;
return ((float) sum / size);
printf (“\nAverage is %f”, }
avg (x, n));
}
November 6, 2024 30
Structures Revisited
November 6, 2024 31
Arrays of Structures
November 6, 2024 32
Example: Sorting by Roll Numbers
#include <stdio.h> for (k=0; k<n; k++)
struct stud scanf (“%d %s %f”, &class[k].roll,
{ class[k].dept_code, &class[k].cgpa);
int roll; for (j=0; j<n-1; j++)
char dept_code[25]; for (k=j+1; k<n; k++)
float cgpa; {
}; if (class[j].roll > class[k].roll)
{
main() t = class[j] ;
{ class[j] = class[k] ;
struc stud class[100], t; class[k] = t
int j, k, n; }
}
scanf (“%d”, &n); <<<< PRINT THE RECORDS >>>>
/* no. of students */ }
November 6, 2024 33
Pointers and Structures
November 6, 2024 34
– 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.
November 6, 2024 35
• Once ptr points to a structure variable, the
members can be accessed as:
ptr –> roll ;
ptr –> dept_code ;
ptr –> cgpa ;
November 6, 2024 36
Example
#include <stdio.h> swap_ref(_COMPLEX *a, _COMPLEX *b)
{
typedef struct { _COMPLEX tmp;
float real; tmp=*a;
float imag; *a=*b;
} _COMPLEX; *b=tmp;
}
main()
print(_COMPLEX *a)
{
{
_COMPLEX x={10.0,3.0}, y={-20.0,4.0};
printf("(%f,%f)\n",a->real,a->imag);
}
(10.000000,3.000000) print(&x); print(&y);
(-20.000000,4.000000) swap_ref(&x,&y);
(-20.000000,4.000000) print(&x); print(&y);
(10.000000,3.000000)
November 6, 2024 } 37
A Warning
November 6, 2024 38
Structures and Functions
November 6, 2024 39
Example: complex number addition
#include <stdio.h> struct complex add (x, y)
struct complex { struct complex x, y;
float re; {
float im; struct complex t;
};
t.re = x.re + y.re ;
main() t.im = x.im + y.im ;
{ return (t) ;
struct complex a, b, c; }
scanf (“%f %f”, &a.re, &a.im);
scanf (“%f %f”, &b.re, &b.im);
c = add (a, b) ;
printf (“\n %f %f”, c.re, c.im);
}
November 6, 2024 40
Example: Alternative way using pointers
#include <stdio.h> void add (x, y, t)
struct complex { struct complex *x, *y, *t;
float re; {
float im; t->re = x->re + y->re ;
}; t->im = x->im + y->im ;
}
main()
{
struct complex a, b, c;
scanf (“%f %f”, &a.re, &a.im);
scanf (“%f %f”, &b.re, &b.im);
add (&a, &b, &c) ;
printf (“\n %f %f”, c,re, c.im);
}
November 6, 2024 41
Dynamic Memory Allocation
November 6, 2024 42
Basic Idea
November 6, 2024 43
Contd.
November 6, 2024 44
Memory Allocation Process in C
November 6, 2024 45
Contd.
November 6, 2024 46
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.
November 6, 2024 47
Allocating a Block of Memory
November 6, 2024 48
Contd.
• 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
November 6, 2024 49
Contd.
November 6, 2024 50
Points to Note
November 6, 2024 51
Example
#include <stdio.h> printf("Input heights for %d
Input the number of students. students \n",N);
main() for(i=0;i<N;i++)
5
{ scanf("%f",&height[i]);
Input heights for 5 students
int i,N;
23 24 25 26 27
float *height; for(i=0;i<N;i++)
Average height= 25.000000
float sum=0,avg; sum+=height[i];
November 6, 2024 52
Releasing the Used Space
November 6, 2024 53
Altering the Size of a Block
November 6, 2024 55
November 6, 2024 56
Pointer to Pointer
• Example:
int **p;
p=(int **) malloc(3 * sizeof(int *));
p[0]
p int ** int *
p[1] int *
int *
p[2]
November 6, 2024 57
2-D Array Allocation
#include <stdio.h> void read_data(int **p,int h,int w)
#include <stdlib.h> {
int i,j;
int **allocate(int h, int w) for(i=0;i<h;i++)
{ for(j=0;j<w;j++)
int **p; Allocate array scanf ("%d",&p[i][j]);
int i,j; of pointers }
Elements accessed
p=(int **) calloc(h, sizeof (int *) );
like 2-D array elements.
for(i=0;i<h;i++)
p[i]=(int *) calloc(w,sizeof (int));
return(p);
} Allocate array of
integers for each
November 6, 2024 58
row
2-D Array: Contd.
void print_data(int **p,int h,int w) main()
{ {
int i,j; int **p;
for(i=0;i<h;i++) int M,N;
{
for(j=0;j<w;j++) printf("Give M and N \n");
printf("%5d ",p[i][j]);Give M and N scanf("%d%d",&M,&N);
printf("\n"); 33 p=allocate(M,N);
} 123 read_data(p,M,N);
} 456 printf("\n The array read as \n");
789 print_data(p,M,N);
}
The array read
as
November 6, 2024 1 2 3 59
4 5 6
typedef in c
November 6, 2024 60
// C program to implement typedef
#include <stdio.h>
int main()
{
// using typedef name to declare variable
ll var = 20;
printf("%ld", var);
return 0;
}
Output
20
November 6, 2024 61
Use of typedef in C
November 6, 2024 62
Using typedef to define a name for a
structure
#include <stdio.h>
#include <string.h>
typedef struct students {
char name[50];
char branch[50];
int ID_no;
} stu;
int main()
{ stu st;
strcpy(st.name, “Kannan");
strcpy(st.branch, “ECE");
st.ID_no = 108;
printf("Name: %s\n", st.name);
printf("Branch: %s\n", st.branch);
printf("ID_no: %d\n", st.ID_no);
return 0;
}
November 6, 2024 63
typedef with Pointers
#include <stdio.h>
typedef int* ptr;
int main()
{
ptr var;
*var = 20;
#include <stdio.h>
typedef int Arr[4];
int main()
{
Arr temp = { 10, 20, 30, 40 };
printf("typedef using an array\n");
November 6, 2024 66
• // An example program to demonstrate working
• // of enum in C
• #include<stdio.h>
• int main()
• {
• enum week day;
• day = Wed;
• printf("%d",day);
• return 0;
• }
November 6, 2024 67