0% found this document useful (0 votes)
15 views

Pointers

c programming

Uploaded by

Haf hafeefa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Pointers

c programming

Uploaded by

Haf hafeefa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

POINTERS

IN C
POINTERS

Basics of Pointer: declaring pointers, accessing data though


pointers, N U L L pointer, array access using pointers, pass by
reference effect.
File Operations: open, close, read, write, append.
Sequential access and random access to files: In built file
handling functions-
{rewind(), fseek(), ftell(), feof(),
fread(), fw rite()} Simple programs
covering pointers and files.
Pointers

A pointer is a variable that represents the location (rather than the
value) of a data item, such as a variable or an array element.

Pointer is a variable which can store the address of another
variable.

This variable can be of type int, char, float, array...

The size of the pointer depends on the architecture. However,
in 32-bit architecture the size of a pointer is 2 byte.

Every variable is a memory location and every memory location has
its address defined which can be accessed using ampersand (&)
operator.

& - address in memory / address of operator
Use of Pointers

Pointers can be used to pass information back and forth between a
function and its reference point.

In particular, pointers provide a way to return multiple data items
from a function via function arguments.

Pointers also permit references to other functions to be specified as
arguments to a given function.

This has the effect of passing functions as arguments to the
given function.

Pointers are also closely associated with arrays and therefore
provide an alternate way to access individual array elements.
Use of Pointers ..

Pointers provide a convenient way to represent multidimensional
arrays, allowing a single multidimensional array to be replaced by a
lower-dimensional array of pointers.

This feature permits a group of strings to be represented within a
single array, though the individual strings may differ in length.
Pointer Declaration

Defining / declaring a pointer variable
datatype *var1; // see * before
variable name

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.

Indirection operator is used for accessing the value of a location (or


variable) using pointer.

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

Write a C program to add two numbers using


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);
}

void swap(int *a,


int *b)
{ int temp;
temp =
Pointers And One Dimensional
Arrays

An array name is really a pointer to the first element in
the array.

Array name is actually a constant pointer.

◆ Suppose we int declare
x[5] = an array x as follows:

Suppose the{1,2,3,4,5};
address of x is 1000 and assuming that each integer
requires 4 bytes, the five elements will be stored as follows:


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;

printf (“How many


Numbers? “);
scanf(“%d”,&n);
for (i=0; i<n; i+
+)
scanf(“%d”,
a+i);
printf(“Numbers are :\
n”); for (i=0; i<n; i+
+)
printf(“%d\n”, *(a+i));
}
Example 2
void main()
{
int
a[20], n, i;
Int *p = a;
printf (“How many
Numbers? “);
scanf(“%d”,&n);
for (i=0; i<n; i+
+)
scanf(“%d”,
p+i);
printf(“Numbers are :\
n”); for (i=0; i<n; i+
+)
printf(“%d\n”, *(p+i))
printf("Address of array a:
Example 3
void readarray(int *, void printarray(int *a, int
int); void main() n)
{ {
int i;
int a[20], for (i=0; i<n ; i++)
n; printf(“%d\
scanf(“%d”, n”,*a++);
&n); }
readarray(a,n)
;
printf (“a = %d\
voidn”,
readarray(int
a); *a, int n)
{ printarray(a,n);
int i;
} printf(“Enter %d numbers\
n“, n); for (i=0; i<n; i++)
scanf(“%d”,a+i);
}
Example 3
int StrLen(char
*); void main()
{
char
s[20];
printf(“String :
“);
scanf(“ %[^\
n]”, s);
printf (“Len =
%d\
n”,StrLen(s));
}

int StrLen (char


*s)
{ int len=0
Tutorial
1.Write a function (using pointer parameters) that compare two integer arrays to see
whether they are identical. The function returns 1 if they are identical, 0 otherwise.

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

int a=123, *p,


**pp; p=&a;
pp=&p;
**pp=555;
printf(“a = %d\
n”,a);
Dynamic Memory Allocation

Allocating memory during program execution.

In C language two main library functions are used

malloc()

calloc()
void * malloac (int n)
where n is the number of bytes to be reserved.

void * calloc (n, sizeof(item))


where n is the number of items. Second argument is the
size of an item.

Header file to be included is stdlib.h

In case of malloc() memory is not initialized. But in


case of calloc() memory is initialized.
malloc() Dynamic Memory Allocation

The name "malloc" stands for memory allocation.

The malloc() function reserves a block of memory of the specified
number of bytes.

It returns a pointer of void which can be casted into pointers of any
form.

Syntax of malloc()
ptr = (castType*) malloc(size);

Example ptr = (float*) malloc(100 *



The above statement allocates 400 bytes of memory.
sizeof(float));

Pointer ptr holds the address of the first byte in the allocated memory.The
expression results in a NULL pointer if the memory cannot be allocated.
Dynamic Memory Allocation
calloc()

The name "calloc" stands for contiguous allocation.

The malloc() function allocates memory and leaves the memory uninitialized, whereas
the calloc() function allocates memory and initializes all bits to zero.

Syntax of calloc()

ptr = (castType*)calloc(n, size);


Example:
ptr = (float*) calloc(25, sizeof(float));

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()

ptr = realloc(ptr, x);

Here, ptr is reallocated with a new size


Dynamic Memory Allocation
#include <stdio.h> printf("Enter elements: ");
#include <stdlib.h> for(i = 0; i < n; ++i)
int main() {
{ scanf("%d", ptr + i);
int n, i, *ptr, sum sum += *(ptr + i);
= 0; }
printf("Enter number of elements: ");
scanf("%d", &n); printf("Sum = %d",
ptr = (int*) malloc(n * sizeof(int)); sum);
// if memory cannot be allocated
if(ptr == NULL) // deallocating the memory
{
free(ptr);
printf("Error! memory not allocated.");
exit(0); return 0;
}
}
Dynamic Memory Allocation
#include <stdio.h> printf("Enter elements: ");
#include <stdlib.h> for(i = 0; i < n; ++i)
int main() { scanf("%d", ptr + i);
{ sum += *(ptr + i);
int n, i, *ptr, sum }
= 0;
printf("Enter number of elements: "); printf("Sum = %d", sum);
scanf("%d", &n); free(ptr);
ptr = (int*) calloc(n, sizeof(int)); return 0;
if(ptr == NULL) }
{
printf("Error! memory not allocated.");
exit(0);
}
Dynamic Memory Allocation
printf("The elements of the array are: ");
#include <stdio.h>
for (i = 0; i < n; ++i) {
#include <stdlib.h>
printf("%d, ", ptr[i]);
int main()
}
{
i=n;
int* ptr;
int n, i; printf("\n\nEnter the new size of the array”);
printf("Enter number of elements:"); scanf("%d",&n);
ptr = realloc(ptr, n * sizeof(int));
scanf("%d",&n);
ptr = (int*)calloc(n, sizeof(int)); for (; i < n; ++i) {
if (ptr == NULL) { ptr[i] = i +
1;
printf("Memory not allocated.\n");
}
exit(0);
printf("The elements of the array are: ");
}
for (i = 0; i < n; ++i) {
else { for (i = 0; i < n; ++i)
printf("%d, ", ptr[i]);
ptr[i] = i + 1;
}
}
Dynamic memory allocation ..
Consider the
example #include
<stdlib.h>

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

data type (*ptrvar) [expression 2] - pointer to array


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.

char s[12][20] ={“January”, “February”, “March”, “April”, “May”, ...,


“December”};

char *s[12]={“January”, “February”, “March”, “April”, “May”, ...,


“December”};
Command line arguments

Command line arguments are values given along with
program name in command prompt.

Since OS is invoking the main() function, OS will pass these values as
arguments to the main() function.

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 :

enum tag var1, var2,...., varn;


OR
enum tag {member 1, member 2,.... , member n}
var1,var2,..., varn;

The enumerated variables can have one of the values member 1,
member 2,.... , member n (enumeration constants).

The compiler automatically assigns integer digits beginning with 0 to all
enumeration constants.
enum

The compiler automatically assigns integer digits beginning
with 0 to all enumeration constants.

Means member 1 is assigned 0, member 2 is assigned 1 and
so on.

The automatic assignment can be overrriden by assigning values
explicitly to the enumeration constant.



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));

You might also like