SlideShare a Scribd company logo
Pointers
From variables to their addresses
1
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Basics of pointers
2
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Basic Concept
In memory, every data item occupies one or more contiguous memory cells.
• A cell in memory is typically a byte. 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 the required amount of
memory cells to hold the value of the variable.
• Since every byte in memory has a unique address, this location also has its own (unique)
address. For a multi-byte data, this is usually specified by the address of the first byte.
C allows you to play with addresses.
3
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
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
• & is the “address-of” operator
Example: &xyz
The ‘&’ operator can be used only with a simple variable or an array element.
&distance
&x[0]
Following usages are illegal:
&235 – address of a constant is not defined
&(a+b) – address of an expression is not defined
4
Example
Consider the statement
int xyz = 50;
1380
(xyz)
• 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 (starting) address location chosen is 1380.
• 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 by looking
at whatever is written in the address (&xyz which equals 1380 in this
example).
50
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Pointer Declaration
A pointer is just a C variable whose value is the address of another variable!
Pointer variables must be declared before we use them.
General form:
data_type *pointer_name;
Example:
int *ptr;
Three things are specified in the above declaration:
• The asterisk (*) tells that the variable ptr is a pointer variable.
• ptr will be used to point to a variable of type int.
Just after declaring a pointer, ptr does not actually point to anything yet (remember: a pointer is also a
variable; hence can contain garbage until it is assigned to some specific value). You can iniialize or set
a pointer to the NULL pointer which points nowhere: int *ptr = NULL;
Pointers are variables and are stored in the memory. They too have their own addresses (like &ptr).
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example (Contd.)
int xyz = 50;
int *ptr; // Here ptr is a pointer to an integer
ptr = &xyz;
1380
(xyz)
- - - -
(ptr)
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.
Once ptr has been assigned a valid memory address, the * operator can be used to access the
value at that address. * is the “value-at” operator; can be used only with a pointer variable
50
1380
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
5 5
Example: Making a pointer point to a variable
a: 1026
b: 1036
x: 2044 x x
y: 2056 y y
Given a pointer variable, we can either:
• make it point to (i.e., store the address of) some existing variable, or
• dynamically allocate memory and make it point to it (to be discussed later)
*x = 20;
*y = *x + 3;
y = x;
10
5
1026
1036
20
23
1026
1036
20
23
1026
1026
int a = 10, b = 5;
int *x, *y;
x = &a; y = &b;
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
8
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Things to Remember
Pointers have types, e.g. :
int *count;
float *speed;
Pointer variables should always point to a data item of the same type.
double x;
int *p;
p = &x; // You should not generally do this, compiler will complain
However, type casting can be used in some circumstances – we will see examples later.
p = (int *)&x;
9
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Pointers and arrays
10
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Pointers and Arrays
When an array is declared:
• The array has 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.
11
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example
Consider the declaration:
int x[5] = {1, 2, 3, 4, 5};
int *p;
• Suppose that the base address of x is 2500, and each integer requires 4 bytes.
Element Value Address
Both x and &x[0] have the value 2500.
p = x; and p = &x[0]; are equivalent.
12
x[0] 1 2500
x[1] 2 2504
x[2] 3 2508
x[3] 4 2512
x[4] 5 2516
Example (contd)
• Suppose we assign p = &x[0];
• Now 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+i) gives the address of x[i]
p+1 = &x[1] = 2504 (p+i) is the same as &x[i]
p+2 = &x[2] = 2508
p+3 = &x[3] = 2512
p+4 = &x[4] = 2516
*(p+i) gives the value of x[i]
For any array A, we have: A+i = &A[i] is the address of A[i], and *(A+i) = A[i].
int x[5] = {1, 2, 3, 4, 5};
int *p;
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Printing pointers with %p
#include <stdio.h>
int main ()
{
int A[4] = {2, 3, 5, 7}, i, *p;
for (i=0; i<4; ++i)
printf("&A[%d] = %p, A[%d] = %dn", i, A+i, i, *(A+i));
p = A;
printf("p = %p, &p = %pn", p, &p); return 0;
}
But then, what is &A?
It is not an int pointer.
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
p = 0x7ffd66659050, &p = 0x7ffd66659048
14
Output
&A[0] = 0x7ffd66659050, A[0] = 2
&A[1] = 0x7ffd66659054, A[1] = 3
&A[2] = 0x7ffd66659058, A[2] = 5
&A[3] = 0x7ffd6665905c, A[3] = 7
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Pointer to an array vs pointer to a pointer
#include <stdio.h>
int main ()
{
int A[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2}, *p;
printf("&A + 1 = %pnn", &A + 1);
p = A;
printf("p = %pn", p);
printf("p + 1 = %pn", p + 1);
printf("&p = %pn", &p);
printf("&p + 1 = %pn", &p +
1); return 0;
}
Output
A = 0x7ffd428a9520
A + 1 = 0x7ffd428a9524
&A = 0x7ffd428a9520
&A + 1 = 0x7ffd428a9560
p = 0x7ffd428a9520
p + 1 = 0x7ffd428a9524
&p = 0x7ffd428a9518
&p + 1 = 0x7ffd428a9520
15
printf("A = %pn", A);
printf("A
printf("&A
+ 1 =
=
%pn",
%pn",
A + 1);
&A);
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Pointer expressions
Pointer arithmetic
16
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Pointers in Expressions
Like other variables, pointer variables can be used in expressions.
If p is an int pointer, then *p is an int variable (like any other int variable).
If p1 and p2 are two pointers, the following statements are valid:
sum = (*p1) + (*p2);
prod = (*p1) * (*p2);
*p1 = *p1 + 2;
x = *p1 / *p2 + 5;
17
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
You can do arithmetic on pointers themselves
What are allowed in C?
• Add an integer to a pointer.
• Subtract an integer from a pointer.
• Subtract one pointer from another.
• If p1 and p2 are both pointers to the same array, then p2–p1 gives the number of
elements between p1 and p2.
18
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Pointer arithmetic
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
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Scale Factor
We have seen that an integer value can be added to or subtracted from a pointer variable.
int x[5] = {10, 20, 30, 40, 50};
int *p;
p = &x[1];
printf
p++;
(“%d”, *p);
//
// This will print 20
This increases p by the number of bytes for int
printf (“%d”, *p); // This will print 30
p = p + 2; // This increases p by twice the sizeof(int)
printf (“%d”, *p); // This will print 50
20
More on Scale Factor
char carr[5] = {‘A’, ‘B’, ‘p’, ‘?’, ‘S’};
int darr[5] = {10, 20, 30, 40, 50}
char *p; int *q;
p = carr; // The pointer p now points to the first element of carr
q = darr; // The pointer q now points to the first element of darr
p = p + 1; // Now p points to the second element in the array “carr”
q = q + 1; // Now q points to the second element in the array “darr”
When a pointer variable is increased by 1, the increment is not necessarily by one byte, but by the size of the data
type to which the pointer points.
This is why pointers have types (like int pointers, char pointers). They are not just a single “address” data type.
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
21
Pointer types and scale factor
Data Type Scale Factor
char 1
int 4
float 4
double 8
• If p1 is an int pointer, then
p1++
will increment the value of p1 by 4.
• If p2 is a double pointer, then
p2--
will decrement the value of p2 by 8.
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Scale factor may be machine dependent
• The exact scale factor may vary from one machine to another.
• Can be found out using the sizeof operator.
• You can supply a variable name or a variable type to it to get its size.
#include <stdio.h>
main( )
{
printf (“No. of bytes occupied by int is %d n”, sizeof(int));
printf (“No. of bytes occupied by float is %d n”, sizeof(float));
printf (“No. of bytes occupied by double is %d n”,
sizeof(double)); printf (“No. of bytes occupied by char is %d n”,
sizeof(char));
}
Output
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
23
Number of bytes occupied by
int is 4 Number of bytes
occupied by float is 4 Number
of bytes occupied by double is
8 Number of bytes occupied
by char is 1
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example of scale factors
#include <stdio.h>
int main ()
{
char C[10], *cp;
int I[20], *ip;
float F[30], *fp;
double D[40], *dp;
cp = C; printf("cp = %p, cp + 1 = %pn", cp, cp+1);
ip = I; printf("ip = %p, ip + 1 = %pn", ip, ip+1);
fp = F; printf("fp = %p, fp + 1 = %pn", fp, fp+1);
dp = D; printf("dp = %p, dp + 1 = %pn", dp, dp+1);
return 0;
} Output
cp = 0x7ffd297f1d8e, cp + 1 =
0x7ffd297f1d8f ip = 0x7ffd297f1b70, ip + 1
= 0x7ffd297f1b74 fp = 0x7ffd297f1bc0, fp +
1 = 0x7ffd297f1bc4 dp = 0x7ffd297f1c40, dp
+ 1 = 0x7ffd297f1c48
24
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Pointers and functions
25
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Passing pointers to a function
In C, arguments are passed to a function by value.
• The data items are copied to the function.
• Changes made in the called function are not reflected in the calling function.
Pointers are often passed to a function as arguments.
• Allows data items within the calling function to be accessed by the called function
(through their address) and modified.
26
Output
a = 5, b = 20
Output
a = 20, b = 5
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Passing pointers as arguments to functions
27
}
int t;
t = x; x = y; y = t;
swap (int x, int y)
void
{
int main()
{
int a, b;
a = 5; b = 20;
swap (a, b);
printf (“a = %d, b = %dn”, a, b);
}
<stdio.h>
#include
void swap (int *x, int *y)
{
int t;
t = *x; *x = *y; *y = t;
}
int main()
{
int a, b;
a = 5; b = 20;
swap (&a, &b);
printf (“a = %d, b = %dn”, a, b);
}
<stdio.h>
#include
A useful application of pointers
In C, a function can only return a single value.
Suppose you want to write a function that computes two values. How to send both the
computed values back to the calling function (e.g., main function)?
One way:
- Declare variables within the main (calling) function.
- Pass addresses of these variables as arguments to the function.
- The called function can directly store the computed values in the variables declared
within main.
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
*p = a + b;
*q = a - b;
return a * b;
}
int main ()
{
Output
x = 89, y = 21, z = 1870
Example of “returning” multiple values using pointers
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
29
}
int u = 55, v = 34, x, y, z;
z = f (u, v, &x, &y);
printf(“x = %d, y = %d, z = %dn”, x, y, z);
int a, int b, int *p, int *q )
f (
int
{
#include <stdio.h>
Pointers or arrays in function prototypes?
There is no difference among the following functions prototypes.
... func_name ( int A[], ... );
... func_name ( int A[100], ... );
... func_name ( int *A, ... );
In all the cases, A is an int pointer. It does not matter whether the actual parameter is the name of an int array or of
an int pointer. Inside the function, A is a copy of the address passed.
For readability, use the following convention.
● If the parameter passed is a pointer to an individual item (like x = &a in the swap example), use the pointer
notation in the function prototype.
● If the parameter passed is an array, you can use any of the two notations in the function prototype. The array
notation may be preferred for readability.
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
30
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
A function can return a pointer
A program to locate the first upper-case letter (if any) in a string
#include <stdio.h>
char *firstupper ( char S[] ) // You can use char *S as the formal parameter
{
while (*S) if ((*S >= ‘A’) && (*S <= ‘Z’)) return S; else ++S;
return NULL;
}
int main ()
{
char *p, S[100];
scanf(“%s”, S);
p = firstupper(S);
if (p) printf(“%c foundn”, *p); else printf(“No upper-case letter foundn”);
return 0;
}
Note: A function should not return a pointer to a local variable. After the function returns, the local variable no longer exists.
31
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Another application of Pointers:
Dynamic memory allocation
32
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Problem with arrays
Sometimes:
• Amount of data cannot be predicted beforehand (may be driven by user input).
• Number of data items keeps changing during program execution.
Example: Search for an element in an array of N elements
One solution: assume a maximum possible value of N and allocate an array of
N elements.
• Wastes memory space, as N may be much smaller in some executions.
• Example: maximum value of N may be 10,000, but a particular run may need to search
only among 100 elements.
• Using array of size 10,000 always wastes memory in most cases.
• On the other extreme, the program cannot handle N larger than 10,000.
3
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Better solution
Dynamic memory allocation
• Know how much memory is needed after the program is run
• Example: ask the user to enter from keyboard
• Dynamically allocate only the amount of memory needed
C provides functions to dynamically allocate memory
• malloc, calloc, realloc
34
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Dynamic Memory Allocation
Normally the number of elements in an array is pre-specified in the program.
• Often leads to wastage of 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.
35
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
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 first byte of the memory.
free
• Frees previously allocated space.
realloc
• Modifies the size of previously allocated space.
6
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
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 returned pointer can be type-casted to any pointer type.
General format:
ptr = (type *) malloc (byte_size);
37
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Allocating a Block of Memory
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
38
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Allocating a Block of Memory
cptr = (char *) malloc (20);
• Allocates 20 bytes of space for the pointer cptr of type char *.
39
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
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.
if ((p = (int *) malloc(100 * sizeof(int))) == NULL)
{ printf (“Memory cannot be allocatedn”);
exit(1);
}
You can use exit(status) instead of return status. For using exit(), you
need to #include <stdlib.h>.
40
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example of dynamic memory allocation
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int *A, n, i;
printf(“How many integers will you enter? ”); scanf(“%d”, &n);
if (n <= 0) { printf(“Wow! How come?n”); exit(1); }
A = (int
if (A ==
*)malloc(n * sizeof(int));
NULL) { printf(“Oops! I cannot store so many integers.n”); exit(2); }
for (i=0; i<n; ++i) {
printf(“Enter integer no. %d: “, i); scanf(“%d”, A+i);
}
/* Now, do what you want to do with the integers read and stored in A[] */
...
exit(0);
}
41
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Can we allocate only arrays?
malloc can be used to allocate memory for single variables also:
p = (int *) malloc (sizeof(int));
• Allocates space for a single int, which can be accessed as *p or p[0]
• Single variable allocations are just special case of array allocations
• Array with only one element
Single variable allocations are useful for building linked structures as we will see later.
42
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Using the malloc’d Array
Once the memory is allocated, it can be used with pointers, or with array notation.
Example:
int *p, n, i;
scanf(“%d”, &n);
p = (int *) malloc (n * sizeof(int));
for (i=0; i<n; ++i)
scanf(“%d”, &p[i]);
The n integers allocated can be accessed as *p, *(p+1), *(p+2), ..., *(p+n-1)
or just as p[0], p[1], p[2], ..., p[n-1]
43
Releasing the allocated space: free
An allocated block can be returned to the system for future use, by the free function.
General syntax:
free (ptr);
where ptr is a pointer to a memory block which has been previously created using malloc (or
calloc or realloc).
No size is to be mentioned for the allocated block. The system remembers it. The function frees
the entire block allocated by an earlier malloc() type of call.
ptr must be the starting address of an allocated block. A pointer to the interior of a block cannot
be passed to free().
Dynamically allocated memory stays until explicitly freed or the program terminates.
You cannot free an array A[] defined like this: int A[50];
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
44
int main()
{
int i,N;
float *height;
float sum=0,avg;
printf("Input no. of studentsn");
scanf("%d", &N);
height = (float *)
malloc(N * sizeof(float));
printf("Input heights for %d studentsn",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 = %fn", avg);
free (height);
return 0;
}
Example of free
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
45
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
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 as:
ptr = malloc (size);
then reallocation of space may be done as:
ptr = realloc (ptr, newsize);
46
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Altering the Size of a Block (contd.)
• 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.
47
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example of realloc
int main ()
{
int *A = (int *)malloc(10 * sizeof(int)), allocsize = 10, n = 0, x;
printf(“Keep on entering +ve integers. Enter 0 or a -ve integer to stop.n”);
while (1) {
printf(“Next integer: ”); scanf(“%d”, &x);
if (x <= 0) break;
++n;
if (n > allocsize)
{ allocsize += 10;
A = (int *) realloc(A, allocsize * sizeof(int));
}
A[n-1] = x;
}
A = (int *) realloc(A, n * sizeof(int)); allocsize = n;
// Process the integers read from the user
...
free(A);
return 0;
}
48

More Related Content

Similar to 08-Pointers.docx An array is a linear data structure (20)

PPTX
4 Pointers.pptx
aarockiaabinsAPIICSE
 
PPTX
Engineering Computers L32-L33-Pointers.pptx
happycocoman
 
PPTX
COM1407: Working with Pointers
Hemantha Kulathilake
 
PPTX
UNIT 4 POINTERS.pptx pointers pptx for basic c language
wwwskrilikeyou
 
PPTX
Pointers in c - Mohammad Salman
MohammadSalman129
 
PPT
ch08.ppt
NewsMogul
 
PPTX
Pointers and single &multi dimentionalarrays.pptx
Ramakrishna Reddy Bijjam
 
PPT
Unit 6 pointers
George Erfesoglou
 
PPT
SPC Unit 3
SIMONTHOMAS S
 
PDF
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
sudhakargeruganti
 
PDF
Lk module5 pointers
Krishna Nanda
 
PPT
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Jayanshu Gundaniya
 
PPT
Lecture 18 - Pointers
Md. Imran Hossain Showrov
 
PPTX
C++ Pointer | Introduction to programming
mahidazad00
 
PPTX
Pointers
Abhimanyu Mehta
 
PPTX
pointers_final.pptxxxxxxxxxxxxxxxxxxxxxx
assignmenthet
 
PPTX
Unit-I Pointer Data structure.pptx
ajajkhan16
 
PPTX
pointers.pptx
janithlakshan1
 
PPTX
Pointers and Dynamic Memory Allocation
Rabin BK
 
PPTX
Pointers in C Language
madan reddy
 
4 Pointers.pptx
aarockiaabinsAPIICSE
 
Engineering Computers L32-L33-Pointers.pptx
happycocoman
 
COM1407: Working with Pointers
Hemantha Kulathilake
 
UNIT 4 POINTERS.pptx pointers pptx for basic c language
wwwskrilikeyou
 
Pointers in c - Mohammad Salman
MohammadSalman129
 
ch08.ppt
NewsMogul
 
Pointers and single &multi dimentionalarrays.pptx
Ramakrishna Reddy Bijjam
 
Unit 6 pointers
George Erfesoglou
 
SPC Unit 3
SIMONTHOMAS S
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
sudhakargeruganti
 
Lk module5 pointers
Krishna Nanda
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Jayanshu Gundaniya
 
Lecture 18 - Pointers
Md. Imran Hossain Showrov
 
C++ Pointer | Introduction to programming
mahidazad00
 
Pointers
Abhimanyu Mehta
 
pointers_final.pptxxxxxxxxxxxxxxxxxxxxxx
assignmenthet
 
Unit-I Pointer Data structure.pptx
ajajkhan16
 
pointers.pptx
janithlakshan1
 
Pointers and Dynamic Memory Allocation
Rabin BK
 
Pointers in C Language
madan reddy
 

More from bhargavi804095 (20)

PPTX
Reinforcement learning ppt in machine learning.pptx
bhargavi804095
 
PPTX
Presentation-lokesh IMAGES for research.pptx
bhargavi804095
 
PPT
concept on arrays and pointers with examples arrays-pointers.ppt
bhargavi804095
 
PPT
Lec3-coa give sthe information abt instruction set.ppt
bhargavi804095
 
PDF
computerregisters during data and address communication.pdf
bhargavi804095
 
PPT
Computer forensics and cyber security powerpoint presentation
bhargavi804095
 
PPT
chapter1-basic-structure-of-computers.ppt
bhargavi804095
 
PPTX
Ch10_The_STACK_and_Subroutines_Slides.pptx
bhargavi804095
 
PPTX
Lec26.pptx An array is a linear data structure
bhargavi804095
 
PDF
The Greibach normal form is referred to as GNF gnf1.pdf
bhargavi804095
 
PPT
java1.pptjava is programming language, having core and advanced java
bhargavi804095
 
PDF
Big Data Analytics is not something which was just invented yesterday!
bhargavi804095
 
PPT
Apache Spark™ is a multi-language engine for executing data-S5.ppt
bhargavi804095
 
PPTX
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
bhargavi804095
 
PPT
A File is a collection of data stored in the secondary memory. So far data wa...
bhargavi804095
 
PPTX
C++ helps you to format the I/O operations like determining the number of dig...
bhargavi804095
 
PPT
While writing program in any language, you need to use various variables to s...
bhargavi804095
 
PPT
Python is a high-level, general-purpose programming language. Its design phil...
bhargavi804095
 
PPT
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
bhargavi804095
 
PPTX
Graphs in data structures are non-linear data structures made up of a finite ...
bhargavi804095
 
Reinforcement learning ppt in machine learning.pptx
bhargavi804095
 
Presentation-lokesh IMAGES for research.pptx
bhargavi804095
 
concept on arrays and pointers with examples arrays-pointers.ppt
bhargavi804095
 
Lec3-coa give sthe information abt instruction set.ppt
bhargavi804095
 
computerregisters during data and address communication.pdf
bhargavi804095
 
Computer forensics and cyber security powerpoint presentation
bhargavi804095
 
chapter1-basic-structure-of-computers.ppt
bhargavi804095
 
Ch10_The_STACK_and_Subroutines_Slides.pptx
bhargavi804095
 
Lec26.pptx An array is a linear data structure
bhargavi804095
 
The Greibach normal form is referred to as GNF gnf1.pdf
bhargavi804095
 
java1.pptjava is programming language, having core and advanced java
bhargavi804095
 
Big Data Analytics is not something which was just invented yesterday!
bhargavi804095
 
Apache Spark™ is a multi-language engine for executing data-S5.ppt
bhargavi804095
 
C++ was developed by Bjarne Stroustrup, as an extension to the C language. cp...
bhargavi804095
 
A File is a collection of data stored in the secondary memory. So far data wa...
bhargavi804095
 
C++ helps you to format the I/O operations like determining the number of dig...
bhargavi804095
 
While writing program in any language, you need to use various variables to s...
bhargavi804095
 
Python is a high-level, general-purpose programming language. Its design phil...
bhargavi804095
 
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
bhargavi804095
 
Graphs in data structures are non-linear data structures made up of a finite ...
bhargavi804095
 
Ad

Recently uploaded (20)

PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PDF
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
PDF
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PPTX
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
PPT
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PDF
mbse_An_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPT
Testing and final inspection of a solar PV system
MuhammadSanni2
 
PPTX
Final Major project a b c d e f g h i j k l m
bharathpsnab
 
PPTX
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
PPTX
MODULE 04 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PPTX
Distribution reservoir and service storage pptx
dhanashree78
 
PPTX
MODULE 05 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PPTX
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PDF
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
REINFORCEMENT LEARNING IN DECISION MAKING SEMINAR REPORT
anushaashraf20
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
mbse_An_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Testing and final inspection of a solar PV system
MuhammadSanni2
 
Final Major project a b c d e f g h i j k l m
bharathpsnab
 
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
MODULE 04 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
Distribution reservoir and service storage pptx
dhanashree78
 
MODULE 05 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
3rd International Conference on Machine Learning and IoT (MLIoT 2025)
ClaraZara1
 
Ad

08-Pointers.docx An array is a linear data structure

  • 1. Pointers From variables to their addresses 1 INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
  • 2. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Basics of pointers 2
  • 3. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Basic Concept In memory, every data item occupies one or more contiguous memory cells. • A cell in memory is typically a byte. 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 the required amount of memory cells to hold the value of the variable. • Since every byte in memory has a unique address, this location also has its own (unique) address. For a multi-byte data, this is usually specified by the address of the first byte. C allows you to play with addresses. 3
  • 4. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 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 • & is the “address-of” operator Example: &xyz The ‘&’ operator can be used only with a simple variable or an array element. &distance &x[0] Following usages are illegal: &235 – address of a constant is not defined &(a+b) – address of an expression is not defined 4
  • 5. Example Consider the statement int xyz = 50; 1380 (xyz) • 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 (starting) address location chosen is 1380. • 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 by looking at whatever is written in the address (&xyz which equals 1380 in this example). 50
  • 6. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
  • 7. Pointer Declaration A pointer is just a C variable whose value is the address of another variable! Pointer variables must be declared before we use them. General form: data_type *pointer_name; Example: int *ptr; Three things are specified in the above declaration: • The asterisk (*) tells that the variable ptr is a pointer variable. • ptr will be used to point to a variable of type int. Just after declaring a pointer, ptr does not actually point to anything yet (remember: a pointer is also a variable; hence can contain garbage until it is assigned to some specific value). You can iniialize or set a pointer to the NULL pointer which points nowhere: int *ptr = NULL; Pointers are variables and are stored in the memory. They too have their own addresses (like &ptr).
  • 8. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
  • 9. Example (Contd.) int xyz = 50; int *ptr; // Here ptr is a pointer to an integer ptr = &xyz; 1380 (xyz) - - - - (ptr) 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. Once ptr has been assigned a valid memory address, the * operator can be used to access the value at that address. * is the “value-at” operator; can be used only with a pointer variable 50 1380
  • 10. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
  • 11. 5 5 Example: Making a pointer point to a variable a: 1026 b: 1036 x: 2044 x x y: 2056 y y Given a pointer variable, we can either: • make it point to (i.e., store the address of) some existing variable, or • dynamically allocate memory and make it point to it (to be discussed later) *x = 20; *y = *x + 3; y = x; 10 5 1026 1036 20 23 1026 1036 20 23 1026 1026 int a = 10, b = 5; int *x, *y; x = &a; y = &b;
  • 12. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 8
  • 13. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Things to Remember Pointers have types, e.g. : int *count; float *speed; Pointer variables should always point to a data item of the same type. double x; int *p; p = &x; // You should not generally do this, compiler will complain However, type casting can be used in some circumstances – we will see examples later. p = (int *)&x; 9
  • 14. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Pointers and arrays 10
  • 15. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Pointers and Arrays When an array is declared: • The array has 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. 11
  • 16. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Example Consider the declaration: int x[5] = {1, 2, 3, 4, 5}; int *p; • Suppose that the base address of x is 2500, and each integer requires 4 bytes. Element Value Address Both x and &x[0] have the value 2500. p = x; and p = &x[0]; are equivalent. 12 x[0] 1 2500 x[1] 2 2504 x[2] 3 2508 x[3] 4 2512 x[4] 5 2516
  • 17. Example (contd) • Suppose we assign p = &x[0]; • Now 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+i) gives the address of x[i] p+1 = &x[1] = 2504 (p+i) is the same as &x[i] p+2 = &x[2] = 2508 p+3 = &x[3] = 2512 p+4 = &x[4] = 2516 *(p+i) gives the value of x[i] For any array A, we have: A+i = &A[i] is the address of A[i], and *(A+i) = A[i]. int x[5] = {1, 2, 3, 4, 5}; int *p;
  • 18. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
  • 19. Printing pointers with %p #include <stdio.h> int main () { int A[4] = {2, 3, 5, 7}, i, *p; for (i=0; i<4; ++i) printf("&A[%d] = %p, A[%d] = %dn", i, A+i, i, *(A+i)); p = A; printf("p = %p, &p = %pn", p, &p); return 0; } But then, what is &A? It is not an int pointer. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR p = 0x7ffd66659050, &p = 0x7ffd66659048 14 Output &A[0] = 0x7ffd66659050, A[0] = 2 &A[1] = 0x7ffd66659054, A[1] = 3 &A[2] = 0x7ffd66659058, A[2] = 5 &A[3] = 0x7ffd6665905c, A[3] = 7
  • 20. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Pointer to an array vs pointer to a pointer #include <stdio.h> int main () { int A[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2}, *p; printf("&A + 1 = %pnn", &A + 1); p = A; printf("p = %pn", p); printf("p + 1 = %pn", p + 1); printf("&p = %pn", &p); printf("&p + 1 = %pn", &p + 1); return 0; } Output A = 0x7ffd428a9520 A + 1 = 0x7ffd428a9524 &A = 0x7ffd428a9520 &A + 1 = 0x7ffd428a9560 p = 0x7ffd428a9520 p + 1 = 0x7ffd428a9524 &p = 0x7ffd428a9518 &p + 1 = 0x7ffd428a9520 15 printf("A = %pn", A); printf("A printf("&A + 1 = = %pn", %pn", A + 1); &A);
  • 21. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Pointer expressions Pointer arithmetic 16
  • 22. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Pointers in Expressions Like other variables, pointer variables can be used in expressions. If p is an int pointer, then *p is an int variable (like any other int variable). If p1 and p2 are two pointers, the following statements are valid: sum = (*p1) + (*p2); prod = (*p1) * (*p2); *p1 = *p1 + 2; x = *p1 / *p2 + 5; 17
  • 23. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR You can do arithmetic on pointers themselves What are allowed in C? • Add an integer to a pointer. • Subtract an integer from a pointer. • Subtract one pointer from another. • If p1 and p2 are both pointers to the same array, then p2–p1 gives the number of elements between p1 and p2. 18
  • 24. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Pointer arithmetic 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
  • 25. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Scale Factor We have seen that an integer value can be added to or subtracted from a pointer variable. int x[5] = {10, 20, 30, 40, 50}; int *p; p = &x[1]; printf p++; (“%d”, *p); // // This will print 20 This increases p by the number of bytes for int printf (“%d”, *p); // This will print 30 p = p + 2; // This increases p by twice the sizeof(int) printf (“%d”, *p); // This will print 50 20
  • 26. More on Scale Factor char carr[5] = {‘A’, ‘B’, ‘p’, ‘?’, ‘S’}; int darr[5] = {10, 20, 30, 40, 50} char *p; int *q; p = carr; // The pointer p now points to the first element of carr q = darr; // The pointer q now points to the first element of darr p = p + 1; // Now p points to the second element in the array “carr” q = q + 1; // Now q points to the second element in the array “darr” When a pointer variable is increased by 1, the increment is not necessarily by one byte, but by the size of the data type to which the pointer points. This is why pointers have types (like int pointers, char pointers). They are not just a single “address” data type. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 21
  • 27. Pointer types and scale factor Data Type Scale Factor char 1 int 4 float 4 double 8 • If p1 is an int pointer, then p1++ will increment the value of p1 by 4. • If p2 is a double pointer, then p2-- will decrement the value of p2 by 8.
  • 28. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
  • 29. Scale factor may be machine dependent • The exact scale factor may vary from one machine to another. • Can be found out using the sizeof operator. • You can supply a variable name or a variable type to it to get its size. #include <stdio.h> main( ) { printf (“No. of bytes occupied by int is %d n”, sizeof(int)); printf (“No. of bytes occupied by float is %d n”, sizeof(float)); printf (“No. of bytes occupied by double is %d n”, sizeof(double)); printf (“No. of bytes occupied by char is %d n”, sizeof(char)); } Output INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 23
  • 30. Number of bytes occupied by int is 4 Number of bytes occupied by float is 4 Number of bytes occupied by double is 8 Number of bytes occupied by char is 1
  • 31. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Example of scale factors #include <stdio.h> int main () { char C[10], *cp; int I[20], *ip; float F[30], *fp; double D[40], *dp; cp = C; printf("cp = %p, cp + 1 = %pn", cp, cp+1); ip = I; printf("ip = %p, ip + 1 = %pn", ip, ip+1); fp = F; printf("fp = %p, fp + 1 = %pn", fp, fp+1); dp = D; printf("dp = %p, dp + 1 = %pn", dp, dp+1); return 0; } Output cp = 0x7ffd297f1d8e, cp + 1 = 0x7ffd297f1d8f ip = 0x7ffd297f1b70, ip + 1 = 0x7ffd297f1b74 fp = 0x7ffd297f1bc0, fp + 1 = 0x7ffd297f1bc4 dp = 0x7ffd297f1c40, dp + 1 = 0x7ffd297f1c48 24
  • 32. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Pointers and functions 25
  • 33. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Passing pointers to a function In C, arguments are passed to a function by value. • The data items are copied to the function. • Changes made in the called function are not reflected in the calling function. Pointers are often passed to a function as arguments. • Allows data items within the calling function to be accessed by the called function (through their address) and modified. 26
  • 34. Output a = 5, b = 20 Output a = 20, b = 5 INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Passing pointers as arguments to functions 27 } int t; t = x; x = y; y = t; swap (int x, int y) void { int main() { int a, b; a = 5; b = 20; swap (a, b); printf (“a = %d, b = %dn”, a, b); } <stdio.h> #include void swap (int *x, int *y) { int t; t = *x; *x = *y; *y = t; } int main() { int a, b; a = 5; b = 20; swap (&a, &b); printf (“a = %d, b = %dn”, a, b); } <stdio.h> #include
  • 35. A useful application of pointers In C, a function can only return a single value. Suppose you want to write a function that computes two values. How to send both the computed values back to the calling function (e.g., main function)? One way: - Declare variables within the main (calling) function. - Pass addresses of these variables as arguments to the function. - The called function can directly store the computed values in the variables declared within main.
  • 36. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
  • 37. *p = a + b; *q = a - b; return a * b; } int main () { Output x = 89, y = 21, z = 1870 Example of “returning” multiple values using pointers INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 29 } int u = 55, v = 34, x, y, z; z = f (u, v, &x, &y); printf(“x = %d, y = %d, z = %dn”, x, y, z); int a, int b, int *p, int *q ) f ( int { #include <stdio.h>
  • 38. Pointers or arrays in function prototypes? There is no difference among the following functions prototypes. ... func_name ( int A[], ... ); ... func_name ( int A[100], ... ); ... func_name ( int *A, ... ); In all the cases, A is an int pointer. It does not matter whether the actual parameter is the name of an int array or of an int pointer. Inside the function, A is a copy of the address passed. For readability, use the following convention. ● If the parameter passed is a pointer to an individual item (like x = &a in the swap example), use the pointer notation in the function prototype. ● If the parameter passed is an array, you can use any of the two notations in the function prototype. The array notation may be preferred for readability. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 30
  • 39. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR A function can return a pointer A program to locate the first upper-case letter (if any) in a string #include <stdio.h> char *firstupper ( char S[] ) // You can use char *S as the formal parameter { while (*S) if ((*S >= ‘A’) && (*S <= ‘Z’)) return S; else ++S; return NULL; } int main () { char *p, S[100]; scanf(“%s”, S); p = firstupper(S); if (p) printf(“%c foundn”, *p); else printf(“No upper-case letter foundn”); return 0; } Note: A function should not return a pointer to a local variable. After the function returns, the local variable no longer exists. 31
  • 40. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Another application of Pointers: Dynamic memory allocation 32
  • 41. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Problem with arrays Sometimes: • Amount of data cannot be predicted beforehand (may be driven by user input). • Number of data items keeps changing during program execution. Example: Search for an element in an array of N elements One solution: assume a maximum possible value of N and allocate an array of N elements. • Wastes memory space, as N may be much smaller in some executions. • Example: maximum value of N may be 10,000, but a particular run may need to search only among 100 elements. • Using array of size 10,000 always wastes memory in most cases. • On the other extreme, the program cannot handle N larger than 10,000. 3
  • 42. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Better solution Dynamic memory allocation • Know how much memory is needed after the program is run • Example: ask the user to enter from keyboard • Dynamically allocate only the amount of memory needed C provides functions to dynamically allocate memory • malloc, calloc, realloc 34
  • 43. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Dynamic Memory Allocation Normally the number of elements in an array is pre-specified in the program. • Often leads to wastage of 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. 35
  • 44. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 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 first byte of the memory. free • Frees previously allocated space. realloc • Modifies the size of previously allocated space. 6
  • 45. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 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 returned pointer can be type-casted to any pointer type. General format: ptr = (type *) malloc (byte_size); 37
  • 46. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Allocating a Block of Memory 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 38
  • 47. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Allocating a Block of Memory cptr = (char *) malloc (20); • Allocates 20 bytes of space for the pointer cptr of type char *. 39
  • 48. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 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. if ((p = (int *) malloc(100 * sizeof(int))) == NULL) { printf (“Memory cannot be allocatedn”); exit(1); } You can use exit(status) instead of return status. For using exit(), you need to #include <stdlib.h>. 40
  • 49. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Example of dynamic memory allocation #include <stdio.h> #include <stdlib.h> int main () { int *A, n, i; printf(“How many integers will you enter? ”); scanf(“%d”, &n); if (n <= 0) { printf(“Wow! How come?n”); exit(1); } A = (int if (A == *)malloc(n * sizeof(int)); NULL) { printf(“Oops! I cannot store so many integers.n”); exit(2); } for (i=0; i<n; ++i) { printf(“Enter integer no. %d: “, i); scanf(“%d”, A+i); } /* Now, do what you want to do with the integers read and stored in A[] */ ... exit(0); } 41
  • 50. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Can we allocate only arrays? malloc can be used to allocate memory for single variables also: p = (int *) malloc (sizeof(int)); • Allocates space for a single int, which can be accessed as *p or p[0] • Single variable allocations are just special case of array allocations • Array with only one element Single variable allocations are useful for building linked structures as we will see later. 42
  • 51. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Using the malloc’d Array Once the memory is allocated, it can be used with pointers, or with array notation. Example: int *p, n, i; scanf(“%d”, &n); p = (int *) malloc (n * sizeof(int)); for (i=0; i<n; ++i) scanf(“%d”, &p[i]); The n integers allocated can be accessed as *p, *(p+1), *(p+2), ..., *(p+n-1) or just as p[0], p[1], p[2], ..., p[n-1] 43
  • 52. Releasing the allocated space: free An allocated block can be returned to the system for future use, by the free function. General syntax: free (ptr); where ptr is a pointer to a memory block which has been previously created using malloc (or calloc or realloc). No size is to be mentioned for the allocated block. The system remembers it. The function frees the entire block allocated by an earlier malloc() type of call. ptr must be the starting address of an allocated block. A pointer to the interior of a block cannot be passed to free(). Dynamically allocated memory stays until explicitly freed or the program terminates. You cannot free an array A[] defined like this: int A[50]; INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 44
  • 53. int main() { int i,N; float *height; float sum=0,avg; printf("Input no. of studentsn"); scanf("%d", &N); height = (float *) malloc(N * sizeof(float)); printf("Input heights for %d studentsn",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 = %fn", avg); free (height); return 0; } Example of free INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 45
  • 54. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 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 as: ptr = malloc (size); then reallocation of space may be done as: ptr = realloc (ptr, newsize); 46
  • 55. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Altering the Size of a Block (contd.) • 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. 47
  • 56. INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Example of realloc int main () { int *A = (int *)malloc(10 * sizeof(int)), allocsize = 10, n = 0, x; printf(“Keep on entering +ve integers. Enter 0 or a -ve integer to stop.n”); while (1) { printf(“Next integer: ”); scanf(“%d”, &x); if (x <= 0) break; ++n; if (n > allocsize) { allocsize += 10; A = (int *) realloc(A, allocsize * sizeof(int)); } A[n-1] = x; } A = (int *) realloc(A, n * sizeof(int)); allocsize = n; // Process the integers read from the user ... free(A); return 0; } 48