Pointers
Pointers
IN C
POINTERS
Example :-
int *pa;
Here pa
is a
pointer
to int
variable.
ie. pa
can store
the
address
of an
integer
Indirection operator
* is the indirection operator.
Usage is
*ptrva
r;
Example
:-
int
*pa,
Datatype
a=10; pa is int ( same as that of
of pa * &a) (same as that
datatype
*pa= *pa of
&a; content
means is the location
of a) pointed
to by int
of pa
Aft
er this
Pointer variable usage
void main()
{
int *pv, v=123;
pv = &v;
printf (“Address of v = %p\n”,
&v); printf (“Value of v =
%d\n”, v);
printf (“Address of pv = %p\n”,
&pv); printf (“Value of pv =
%p\n”, pv); printf (“Value of
*pv = %d\n”, *pv);
*pv = 567;
printf (“a=%d\n”,*pv);
}
Operations on Pointers
Operations on Pointers
void main()
{
int
a,b,sum;
int
*p,*q;
a=5,b=6;
p= &
a;
q= &
Passing Pointer to Function
void modify(int
*); void main()
{
int
a=123;
modify(&a);
printf (“a =
%d\n”, a);
}
void modify(int
*p)
{
*p=567;
}
Passing Pointer to Function
void readnum(int
*); void main()
{
int a;
readnum(&a);
printf (“a =
%d\n”, a);
}
void readnum(int
*p)
{
printf(“Enter an integer
: “); scanf(“%d”,p);
}
Passing Pointer to Function
void swap(int *, int
*); void main()
{
int a=10,
b=20;
swap(&a, &b);
printf (“a =
%d\n”, a);
printf (“b =
%d\n”, b);
}
◆
The name x is defined as a constant pointer pointing to the first
element x[0].
Pointers And One Dimensional
Arrays
int *ptr;
From the example, it is clear that &x[0] is
equivalent to x. ptr = x = &x[0] = 1000
ptr + 1 = &x[1] =
1004 ptr + 2 =
&x[2] = 1008
ptr + 3 = &x[3] =
1012 ptr + 4 =
&x[4] = 1016
address of x[3] =
base address + (3
x scale factor of
Pointers And One Dimensional
Arrays
Consider the
example int
a[5];
Here a represents
&a[0] Datatype of
a[0] – int
Datatype of &a[0] –
&a[
int * is a or
0] a+0 is
&a[know that
We a+1an
1]
integerisvalue
a+2can be
&a[
So &a[i]
added toisa pointer.
2]
a+i
a[0] is *a
a[1] is
*(a+1)
Example 1
void main()
{
int a[20], n, i;
2.Write a function (using pointer parameters) that reads n integers, store them in an array
and search for an element in the array using Linear Search algorithm.
Pointer to pointer
◆
Since pointer varible is also having an address, we can store
that address into another pointer variable.
int **p; // pointer to pointer to int
Syntax of calloc()
The above statement allocates contiguous space in memory for 25 elements of type
float.
Dynamic Memory Allocation
free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on
their own. We must explicitly use free() to release the space.
Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
Dynamic Memory Allocation
realloc()
●
If the dynamically allocated memory is insufficient or more than required, you can
change the size of previously allocated memory using the realloc() function.
●
Re-allocation of memory maintains the already present value and new blocks will be
initialized with the default garbage value.
Syntax of realloc()
Void main()
{
int *a, n;
scanf(“%d”,
&n);
a = (int *)
malloc(n *
sizeof(int));
// from here a
can be
treated as an
array of
Pointers and multidimensional arrays
●
A one dimensional array can be represented in terms of a
pointer and an offset.
●
A two dimensional array is actually a collection of one
dimensional arrays.
●
Thus we can define 2D array as a pointer to a group of 1D
arrays.
●
The 2D array declaration can be written as
●
The parentheses that surround the array name is a must.
●
Otherwise it would define an array of pointers rather than
a pointer to a group of arrays
Pointer to Array
●
Suppose x is 2D integer array having 10 rows and 20
columns.
●
We can declare x as
●
int (*x)[20]; rather than x[10][20];
●
In this pointer declaration, x is defined to be a pointer to a group of
contigous, one dimensional, 20 element integer arrays.
●
Thus x, points to the first 20-element array, which is actually the first
row (row 0) of original 2D array.
●
Similarly (x+1) points to the second 20 element array, which is the second
row (row 1) and so on.
●
Accessing individual elements:
x[2][5] – row 2 and column 5 can be accessed as
*(*(x+2)+5) (x+2) – pointer to row 2
Object of this pointer *(x+2) - pointer to first element
in row 2 – address of row 2.
*(x+2)+5) is a pointer to column 5 in row 2. - address
of column 5 in row 2
Pointer to Array
#include<stdlib
.h> int main()
{ printf("%p %p",(*(a+0)),(*(a+1)));
int(*a)[5],(*b)[5],(*c) printf("%p %p",(*(a+0)+2),
[5],i,j,m,n; printf("Enter (*(a+1)+2));
m & n:"); scanf("%d printf("%d
%d",&m,&n); %d",*(*(a+0)+2),*(*(a+1)+2));
a=malloc(m*sizeof(a));
b=malloc(m*sizeof(b));
c=malloc(m*sizeof(c));
printf("Enter 1 matrix:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",(*(a+i)+j));
}
Array of Pointers
●
A multidimensional array can be expressed in terms of an array of
pointers rather than a pointer to a group of contiguous arrays.
●
int *a[5];
●
Here a is an array of pointers.
●
5 locations are reserved and each location can store a
●
pointer to int.
Array of Pointers
●
A multidimensional array can be expressed in terms of an array of
pointers rather than a pointer to a group of contiguous arrays.
●
int *x[10];
●
Here x[0] points to the beginning of the first row.
●
x[1] points to the beginning of second row and so on.
●
The number of elements in each row is not explicitly
specified.
●
x[2] points to the first element in third row
(row 2)
●
(x[2]+5 ) points to *(x+2)
the 6th element in row 2 - same +5
●
as *(*(x+2)
+5)
*(x[2]+5 ) refers to the element at x[2][5] -
same as
#include Array of Pointers
<stdio.h>
#include<stdlib
.h> int main()
{
int printf("%p %p",(*(a+0)),
*a[5],*b[5],*c[5],i,j,m,n,ro (*(a+1))); OR
w; printf("Enter m & n:"); printf("%p %p",a[0],a[1]);
scanf("%d %d",&m,&n);
for(row=0;row<m;row+
+) printf("%d
{ %d",*(*(a+0)+2),*(*(a+1)+2));
a[row]=malloc(n*sizeof(i
OR
nt));
printf("%d
b[row]=malloc(n*sizeof(i
%d",*(a[0]+2),*(a[1]+2));
nt));
c[row]=malloc(n*sizeof(i
nt));
}
printf("Enter 1
Array of Pointers
●
Another use of array of
pointers.
●
Ragged(Jagged) arrays – array of char pointers initilized with string
constants.
void main( int argc, char *argv[ ]) // one use of array of pointers
{
argc – argument
count argv –
argument vector
Command line arguments
#include <stdio.h>
void main(int argc, char
*argv[])
{
int i;
printf ("argc = %d\n\n",
argc); for (i=0; i<argc;
i++)
printf("argv[%d] = %s\n",
i, argv[i]);
}
$ cc filename.c
Command line arguments
#include
<stdio.h>
#include
<stdlib.h>
void main(int
argc, char
*argv[])
{
int i,
sum=0;
float av;
for
(i=1;
Pointers and structure
struct
student {
int rno;
char
name[30]
;
●
Here p is a pointer to struct student.
} s, *p;
●
It can store the address of a variable of type struct
student.
static struct student s1={ 123, “Anil
Kumar”}, *p1; p1 = &s1;
printf (“%d”, p1->rno);
printf (“%d”, (*p1).rno);
Pointers and structure
●
Arrow operator
( ->
) ●
Used to access a member using pointer to structure
variable.
●
pointer_to_structure -> member
●
p1->rno = 555;
Self referential structure
Atleast one of the member of a structure is a pointer to parent
structure type.
struct
node {
int
item;
struct
node
*link;
} *list, *p;
list =
NULL;
p = (struct
node *)
malloc(siz
Self referential structure
Atleast one of the member of a structure is a pointer to parent
structure type.
struct
node {
int
item;
struct
node
*link;
} *list, *p;
list =
NULL;
p = (struct
node *)
malloc(siz
Self referential structure
Atleast one of the member of a structure is a pointer to parent
structure type.
struct
Linked_list {
float salary;
struct
Linked_list
*next;
};
struct Linked_list
node1,node2;
node1.salary=
50000; node1.next
= &node2;
Self referential structure
Atleast one of the member of a structure is a pointer to parent
structure type.
struct
Linked_list {
float salary;
struct
Linked_list
*next;
};
struct Linked_list
*node1,*node2;
node1 = (struct Linked_list *) malloc(sizeof (struct
Linked_list)); node2 = (struct Linked_list *)
malloc(sizeof (struct Linked_list)); node1->salary=
50000;
Pointer to function
●
A pointer to function can be passed to another function as an
●
argument. This allows one function to be transferred to
another , as though the first function were a variable.
●
A pointer to a function is declared as follows
type (*fptr)();
data-type (* function-name)(type1 arg1, type2 arg2 .... )
●
This tells the compiler that fptr is a pointer to a function, which
returns type
●
value.
Parentheses around *fptr are necessary. ( Otherwise type
●
*fptr() - would declare fptr as function returning a pointer to
type.)
EgWe can make a function pointer to point to a specific function
. by simply assigning the name of the function to the pointer.
float mul(int,
int); float
(*fp)(); - (*fp)(a,b); - equivalent to
fp = mul; To mul(a,b);
Pointer to function
#include
<stdio.h> int int sum (int x, int
sum (int, int); y)
int product (int, {
int); void main() return x+y;
{ }
int a,b,s,p; int product(int x,
int (*pf)(int, int y)
int); {
printf("Enter Two return x*y;
integers : "); scanf("%d }
%d", &a,&b); pf=sum;
s=(*pf)(a,b); printf("\
nSum = %d\n",s);
pf=product;
p=(*pf)(a,b);
printf ("\nProduct =
Pointer to function
#include
<stdio.h> int int process (int (*pf)(int, int), int x,
sum (int, int); int y)
int product (int, {
int); int result;
int process(int (*) result = (*pf)
(),int,int); void main() (x,y); return
{ result;
int a,b,s,p; }
printf("Enter Two int sum (int x, int y)
integers : "); scanf("%d {
%d", &a,&b); return x+y;
s=process(sum,a,b); }
printf("\nSum = %d\ int product(int x, int
n",s); y)
p=process(product, a,b); {
printf ("\nProduct = %d\ return x*y;
Declarations
int *p;
int
*p[5];
int (*p)
[5]; int
*p();
int *p(char
*a); int (*p)
(int a);
enum
●
enum keyword is used for creating user defined data
types in C.
Syntax is
enum tag { member 1, member 2,.... , member n};
Declaring a variable :
●
●
Eg. enum day {Monday =
1,Tuesday, .....Sunday};
●
Here Moday is assigned the value of 1.
●
The remaining constants are assigned values that increase
successively by 1.
●
Thus Sunday will be having the value 7.
enum
#include <stdio.h>
enum direction {east, west, north,
south}; enum boolean {false,
true};
enum month { jan=1, feb, mar, apr, may, jun, jul, aug, sep, oct,
nov, dec}; void main()
{
enum boolean prime;
enum month
current=sep;
prime=false;
printf("prime = %d\n", prime);
printf("Current Month = %d\
n",current);
}
enum
#include <stdio.h>
enum month {jan=1, feb, mar, apr, may, jun, jul, aug, sep, oct,
nov, dec}; void main()
{
int mno;
printf ("Enter
month : ");
scanf("%d",&mno);
if (mno>0 && mno
{
<13)case sep :
switch
(mno)case apr :
case jun :
case nov : printf ("No of days : 30\
n");break; case feb : printf ("No of days
28/29\n");break; default : printf ("No
} of days : 31\n");
else printf ("Invalid\
Bit fields
●
So far we have been using integer fields of size 16 bits or 32 bits to
●
store data. There may be occasions where data items
●
require much less than this space. To avoid such memory wastage,
C permits to use small bit fields to hold data items and
●
thereby pack several data items in a word of memory.
A bit field is a set of adjascent bits whose size can be from 1 to
●
16/32 bits in length.
●
A word can therefore be divided into a number of bit
●
fields. The name and size of bit fields are defined
using a structure. The general form of bit field
definition is :
struct tag_name
{
data type name1 : bit-
length;
data data
type type :name2
nameN bit-
: bit-length;
length;
};
Bit fields
●
The data type is either int or unsigned int or signed int and bit-
length is the number of bits used for the specified name.
●
Signed bit field should have at least 2 bits – one bit
●
for sign. The first field always start with first bit of
●
the word.
●
There can be unused bits in a word.
We cannot take the address of a bit field, so we cannot use scanf to
●
read values into bit fields.
Eg . struct personal Access the fields
{ as
unsigned sex : emp.sex =1;
1 unsigned emp.age =
age: 7 50;
unsigned scanf(“%d”,&
children: 3 a); emp.age
unsigned = a;
m_status: 2
Bit fields
#include
<stdio.h> void
main()
{
struct {
unsigned
dd:5;
unsigned
mm:4;
unsigned
yy:6;
}
date={21,0
5,20};
printf ("size : %d\n",
(int)sizeof(date));