KKR & KSR INSTITUTE OF TECHNOLOGY & SCIENCES
(Autonomous)
(Approved by AICTE, Delhi , Permanently Affiliated to JNTUK, Kakinada,
Accredited by NAAC & NBA)
Vinjanampadu, Guntur, Andhra Pradesh
POINTERS
MEMORY ALLOCATION FUNCTIONS
PROCESSOR COMMANDS
Subject: Programming for problem solving using C
Year/Sem: I [Link] I Sem
Class: Civil & Mechanical
Prepared By:
M. Rajesh Reddy,
Assistant Professor,
Department of CSE
POINTERS:
Definition: A Pointer in C language
is a variable which holds the
address of another variable of same
data type.
Concept of Pointers
Whenever a variable is declared in
a program, system allocates a
location i.e an address to that
variable in the memory, to hold the
assigned value.
Eg: Let us assume that system has
allocated memory location 80F for a
variable a.
int a = 10;
int* ptr=&a;
We can access the value 10 either
by using the variable name a or by
using its address 80F
2
A pointer is a variable which holds
an address of some other variable.
The
19 Aprilvalue
2021 of a pointer variable
M. Rajesh Reddy, Assistantgets
Professor, Dept of CSE- KITS (Autonomous)
Benefits of using pointers
Pointers are more efficient in handling Arrays and Structures.
Pointers allow references to function and thereby helps in
passing of function as arguments to other functions.
It reduces length of the program and its execution time as well.
It allows C language to support Dynamic Memory management.
Declaration of Pointer variable
General syntax of pointer declaration is datatype
*pointer_name;
Data type of a pointer must be same as the data type of the
variable to which the pointer variable is pointing.
Eg:
int *ip // pointer to integer variable
float *fp; // pointer to float variable
double *dp; // pointer to double variable 3
char *cp; // pointer to char variable
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Initialization of Pointer variable
Pointer Initialization is the process of assigning address of a
variable to a pointer variable.
Pointer variable can only contain address of a variable of the same
data type.
In C language address operator (&) is used to determine the
address of a variable.
The & (immediately preceding a variable name) returns the address
of the variable associated with it.
Eg:
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
Note: Pointer variable should always point to variables of same
datatype.
Eg:
float a;
int *ptr; 4
ptr = &a; // ERROR, type mismatch.
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Dereferencing of Pointer
Once a pointer has been assigned the address of a
variable, to access the value of the variable, pointer
is de-referenced, using the indirection
operator or de-referencing operator *.
Eg:
int a, *p; // declaring the variable and pointer
a = 10;
p = &a; // initializing the pointer
printf("%d", *p); //this will print the value of 'a'
printf("%d", *&a); //this will also print the value of
'a'
printf("%u", &a); //this will print the address of 'a'
printf("%u", p); //this will also print the address of
'a' 5
printf("%u", &p); //this will print the address of 'p'
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Pointer to an Array
An array name is a constant pointer to the first element of
the array.
Therefore, in the declaration − double balance[50];
balance is a pointer to &balance[0], which is the address of
the first element of the array balance.
Thus, the following program fragment assigns p as the
address of the first element of balance −
double *p;
double balance[10];
p = balance;
It is legal to use array names as constant pointers, and
vice versa. Therefore, *(balance + 2) is a legitimate way of
accessing the data at balance[2].
Once you store the address of the first element in 'p', you
can access the array elements using *p, *(p+1), *(p+2) and
so on. 6
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Example Program:
#include <stdio.h>
int main () {
/* an array with 3 elements */
double balance[3] = {1000.0, 50000.0, 300.4};
double *p; Output:
int i; Array values using pointer
p = balance; *(p + 0) : 1000.00
*(p + 1) :50000.00
/* output each array element's value */ *(p + 2) : 300.40
printf( "Array values using pointer\n");Array values using balance as address
for ( i = 0; i < 3; i++ ) *(balance + 0) : 1000.00
*(balance + 1) : 50000.00
printf("*(p + %d) : %.2f\n", i, *(p + i) );
*(balance + 2) : 300.40
printf( "Array values using balance as address\n");
for ( i = 0; i < 3; i++ )
printf("*(balance + %d) : %.2f\n", i, *(balance + i)
); 7
return 0; 2021
19 April M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Pointer Compatibility
The rules for assigning one pointer to another are tighter than
the rules for numeric types.
For example, you can assign an int value to a double variable
without using a type conversion, but you can’t do the same for
pointers to these two types.
#include <stdio.h>
int main() {
int n = 5;
long double x;
int *pi = &n;
long double *pld = &x;
x = n; /* implicit type conversion */
pld = pi; /* compile-time error */
return 0;
}
8
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Pointer Arithmetic
The following Arithmetic operations can be performed on
pointers
Increment/decrement pointer (++ or --)
Add or Subtract an integer to a pointer( + or += , - or -=)
Pointers may be subtracted from each other
For example, consider integer array with 5 elements on machine with 4
byte for int datatype.
– vPtr points to first element v[ 0 ]
• at location 3000 (vPtr = 3000)
– vPtr += 2; sets vPtr to 3008
• vPtr points to v[ 2 ] (incremented by 2), but the machine has 4
byte for int datatype, so it points to address 3008
location
3000 3004 3008 3012 3016
v[0] v[1] v[2] v[3] v[4]
9
pointer variable vPtr
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Let's take some more examples.
int i = 12, *ip = &i;
double d = 2.3, *dp = &d;
char ch = 'a', *cp = &ch;
Suppose the address of i, d and ch are 1000, 2000, 3000
respectively, therefore ip, dp and cp are at 1000, 2000, 3000
initially.
Pointer Arithmetic on Integers
Pointer
How it is evaluated ?
Expression
ip = ip + 1 ip => ip + 1 => 1000 + 1*4 => 1004
ip++ or ++ip ip => ip + 1 => 1004 + 1*4 => 1008
ip = ip + 5 ip => ip + 5 => 1008 + 5*4 => 1028
ip = ip - 2 ip => ip - 2 => 1028 - 2*4 => 1020
10
ip-- or --ip ip => ip - 1 => 1020 - 1*4 => 1016
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Pointer Arithmetic on double
Pointer Expression How it is evaluated ?
dp + 1 dp = dp + 1 => 2000 + 1*8 => 2008
dp++ or ++dp dp => dp+1 => 2008+1*8 => 2016
dp = dp + 5 dp => dp + 5 => 2016+5*8 => 2056
dp = dp - 2 dp => dp - 2 => 2056-2*8 => 2040
dp-- or --dp dp=> dp - 1=>2040-1*8=>2032
Pointer Arithmetic on characters
Pointer Expression How it is evaluated ?
cp + 1 cp = cp + 1 => 3000 + 1*1 => 3001
cp++ or ++cp cp => cp + 1 => 3001 + 1*1 => 3002
cp = cp + 5 cp => cp + 5 => 3002 + 5*1 => 3007
cp = cp - 2 cp => cp + 5 => 3007 - 2*1 => 3005 11
cp-- or --cp cp => cp - 1 => 3005 - 1*1 => 3004
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Subtraction between two pointers
If we have two pointers p1 and p2 of base type pointer to int
with addresses 1000 and 1016 respectively, then p2 - p1 will give
4, since the size of int type is 4 bytes.
If you subtract p2 from p1 i.e p1 - p2 then the answer will be
negative i.e -4.
Example Output:
Value of ip1 or address of i1 = 2686780
#include<stdio.h> Value of ip2 or address of i2 = 2686788 ip2
int main() { - ip1 = 2
ip1 - ip2 = -2
int i1 = 12, *ip1 = &i1;
int i2 = 12, *ip2 = &i2;
printf("Value of ip1 or address of i1 = %u\n", ip1);
printf("Value of ip2 or address of i2 = %u\n\n", ip2);
printf("ip2 - ip1 = %d\n", ip2 – ip1);
printf("ip1 - ip2 = %d\n", ip1 – ip2);
return 0; 12
}
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Pointer to a Pointer (Double Pointer)
When one pointer variable stores the address of another pointer variable, it is
known as Pointer to Pointer variable or Double Pointer.
Output:
Syntax: Address of a = 2686724
datatype **pointer_name; Address of p1 = 2686728
Address of p2 = 2686732
Simple program to represent Pointer to a Pointer
#include <stdio.h> Value at the address stored
by p2 = 2686724
int main() {
Value at the address stored
int a = 10;
by p1 = 10
int *p1; //pointer variable Value of **p2 = 10
int **p2; //pointer to a pointer
p1 = &a; //store the address of variable a
p2 = &p1; ; //store the address of pointer variable p1 */
printf("Address of a = %u\n", &a);
printf("Address of p1 = %u\n", &p1);
printf("Address of p2 = %u\n\n", &p2);
printf("Value at the address stored by p2 = %u\n", *p2);
printf("Value at the address stored by p1 = %d\n\n", *p1);
printf("Value of **p2 = %d\n", **p2); //read this *(*p2) 13
return 0;
} 19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Pointers and Two-Dimensional Arrays:
Assume that we have a two-dimensional array of integers.
int table[3][4];
When we dereference the array name, we don‟t get one integer, we get an
array of integers. In other words, the dereference of the array name of a
two-dimensional array is a pointer to a one-dimensional array.
Each element in the figure is shown in both index and pointer notation.
Note that table t[0] refers to an array of four integer values. * (table +0)
also refers to an array of four integers.
table [ 0 ] is identical to * ( table + 0 )
To refer to a row, we dereference the array pointer, which gives us a pointer
to a row. Given a pointer to a row, to refer to an individual element, we
dereference the row pointer. This double dereference is given by *(*(table )
)
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++)
printf("%6d", *( *(table + i) + j));
printf( "\n" );
} // for i
14
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Array of Pointers
Just like we can declare an array of int, float or char etc, we can
also declare an array of pointers.
Syntax: datatype *array_name[size];
Example: int *arrop[5]
Here arrop is an array of 5 integer pointers. It means that this
array can hold the address of 5 integer variables
Example Program:
#include<stdio.h>
int main() {
int *arrop[3]; //array of pointers
int a = 10, b = 20, c = 50, i;
Output:
arrop[0] = &a;
Address = 387130656 Value = 10
arrop[1] = &b; Address = 387130660 Value = 20
arrop[2] = &c; Address = 387130664 Value = 50
for(i = 0; i < 3; i++)
printf("Address = %d\t Value = %d\n", arrop[i], *arrop[i]);
return 0;
} 15
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Memory Allocation:
C gives us two choices when we want to reserve memory
locations for an object: static allocation and dynamic
allocation.
Memory is divided into program memory and data
memory.
Program memory consists of the memory used for main
and all called functions.
Data memory consists of permanent definitions, such as
global data and constants, local declarations, and
dynamic data memory.
16
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Static Memory Allocation:
Static memory allocation requires that the declaration and
definition of memory be fully specified in the source
program.
The number of bytes reserved cannot he changed during
run time.
This is the technique we have used to this point to define
variables, arrays, pointers etc.
Dynamic Memory Allocation:
Dynamic memory allocation uses predefined functions to
allocate and release memory or data while the program is
running.
To use dynamic memory allocation, we use either standard
data types or derived types that we have previously
declared.
Dynamic memory allocation has no identifier associated
with it; it has only an address that must be used to access
it. 17
To access data in dynamic memory; therefore, we must use
a19 April
pointer.
2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Memory Allocation Functions:
Four memory management functions are used with dynamic
memory.
Three of them, malloc(), calloc(), and realloc(), are used for
memory allocation. The fourth, free(), is used to return memory
when it is no longer needed.
All the memory management functions are found in the
standard library file (stdlib .h).
1. Block Memory Allocation --malloc():
The malloc() function allocates a block of memory that contains
the number of bytes specified in its parameter. It returns a void
pointer to the first byte of the allocated memory. However, if it is
not successful, it returns NULL pointer
Syntax: ptr = (castType*) malloc(size);
Example:
int * ptr;
/* below statement allocates a memory block of 400 bytes (100*4)
and returns address of starting byte of the block*/
ptr=(int*) malloc(100*sizeof(int)); 18
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
2. Contiguous Memory Allocation– calloc():
The calloc(), is primarily used to allocate memory for arrays.
It differs from malloc() only in that it sets memory to null characters.
Syntax: ptr = (castType*)calloc(n, size);
Example:
float * ptr;
/* below statement allocates contiguous space in memory for 25 elements
of type float.*/
ptr = (float*) calloc(25, sizeof(float));
3. Reallocation of Memory– realloc():
The realloc() function can he highly inefficient and therefore should be
used advisedly.
When given a pointer to a previously allocated block of memory,
realloc() changes the size of the block by deleting or extending the
memory at the end of the block.
Syntax: ptr = realloc(ptr, x);
Here, ptr is reallocated with a new size x.
4. Releasing Memory– free():
When memory locations allocated by malloc(), calloc(), or realloc() arc
no longer needed, they should be freed using the predefined function
free(). 19
Syntax: free(ptr);
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Example program for Dynamic Memory Allocation:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *ptr;
/*below statement allocates 20 bytes of memory block and return
starting address*/
ptr = malloc(20); //or ptr = calloc(20,sizeof(char));
strcpy(ptr," Problem solving ");
printf("ptr : %s\n",ptr);
/*below statement extends the previous block size to 100 bytes and
return starting address*/
ptr = realloc(ptr,100);
strcpy(ptr," Programming for problem solving");
printf("ptr : %s\n",ptr);
free(ptr); OUTPUT:
return 0; ptr : Problem solving
} ptr : Programming for problem
20
solving
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Pre-processor Commands:
The C preprocessor is a program that processes any source
program in C before compilation.
In simple terms, a C Preprocessor is just a text substitution
tool and it instructs the compiler to do required pre-
processing before the actual compilation.
All preprocessor commands begin with a hash symbol (#).
The C Preprocessor Directives:
The preprocessor directives can be classified into two
categories: unconditional and conditional.
21
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Examples
1. #define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of
MAX_ARRAY_LENGTH with 20.
22
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Examples
2. #include <stdio.h>
#include "myheader.h"
The first line tell the CPP to get stdio.h from System
Libraries and add the text to the current source file.
The second line tells CPP to get myheader.h from the local
directory and add the content to the current source file.
3. #undef FILE_SIZE
#define FILE_SIZE 42
It tells the CPP to undefine existing FILE_SIZE and define
it as 42.
4. #ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
It tells the CPP to define MESSAGE only if MESSAGE isn't
already defined.
23
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Example program for #define, #include preprocessors in C
language:
#include <stdio.h>
Output:
value of height : 100
#define height 100 value of number : 3.140000
#define number 3.14 value of letter : A
#define letter 'A' value of letter_sequence : ABC
#define letter_sequence "ABC“
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
} 24
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Example program for undef in C language:
This directive undefines existing macro in the program.
#include <stdio.h> Output:
First defined value for height : 100
Value of height after undef : 600
#define height 100
void main()
{
printf("First defined value for height : %d\n",height);
#undef height // undefining variable
#define height 600 // redefining the same for new
value
printf(“Value of height after undef :%d",height);
} 25
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Example program for #if, #else and #endif in C:
“If” clause statement is included in source file if given
condition is true.
Otherwise, else clause statement is included in source file for
compilation and execution.
#include <stdio.h>
#define a 100 Output:
int main() a is equal to 100
{
#if (a==100)
printf(“a is equal to 100\n");
#else
printf(“a is not equal to 100\n");
#endif
return 0;
}
26
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Example program for #ifdef, #else and #endif in C:
“#ifdef” directive checks whether particular macro is defined or
not. If it is defined, “If” clause statements are included in source
file.
Otherwise, “else” clause statements are included in source file for
compilation and execution.
#include <stdio.h>
#define RAJU 100
Output:
int main() RAJU is defined.
{
#ifdef RAJU
printf("RAJU is defined. \n");
#else
printf("RAJU is not defined\n");
#endif
return 0;
}
27
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Example program for #ifndef and #endif in C:
#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not
defined, “If” clause statements are included in source file.
Otherwise, else clause statements are included in source file for compilation
and execution.
#include <stdio.h>
#define RAJU 100 Output:
int main() SELVA is not defined. So, now we are going to
{ define here
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program”);
#endif
return 0;
}
28
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Predefined Macros
The preprocessor has a small set of predefined macros that
denote useful information. The standard macros are:
1. __DATE__
The current date as a character literal in "MMM DD YYYY"
format.
2. __TIME__
The current time as a character literal in "HH:MM:SS" format.
3. __FILE__
This contains the current filename as a string literal.
4. __LINE__
This contains the current line number as a decimal constant.
29
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)
Example program on pre-defined macros
#include <stdio.h>
int main() {
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
return 0;
}
Output:
File :test.c
Date :Apr 19 2021
Time :10:36:24
Line :8
30
19 April 2021 M. Rajesh Reddy, Assistant Professor, Dept of CSE- KITS (Autonomous)