POINTERS
POINTER S :
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
 A pointer is a variable which holds an
address of some other variable. The
value of a pointer variable gets stored
in another memory location.
2
Advantages 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.
Disadvantages of Pointers:
 Pointers are a little complex to understand.
 Pointers can lead to various errors such as
segmentation faults
or can access a memory location which is not
required at all.
 If an incorrect value is provided to a pointer, it may
cause
memory corruption.
 Pointers are also responsible for memory leakage.
 Programmers find it very difficult to work with the pointers;
therefore it is programmer's responsibility to manipulate a
pointer carefully.
3
Declaring a 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;
char *cp;
// pointer to double variable
/
/ pointer to char variable
4
Initializing a 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;
ptr = &a;
//pointer declaration
//pointer initialization
Note: Pointer variable should always point to variables of same
datatype.
Eg:
float a;
int *ptr;
ptr = &a; // ERR O R, type mismatch.
5
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);
printf("%d", *&a);
printf("%u", &a);
printf("%u", p);
printf("%u", &p);
//this will print the value of 'a'
//this will also print the value of 'a'
//this will print the address of 'a'
//this will also print the address of 'a'
//this will print the address of 'p'
6
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.
7
#include <stdio.h>
int main () {
/* an array with 3 elements */
double balance[3] = {1000.0, 50000.0, 300.4};
double *p;
int i;
p =
balance;
/* output
each array
element's
value */
for ( i = 0; i < 3; i++ )
printf( "Array values using balance as addressn");
for ( i = 0; i < 3; i++ )
printf("*(balance + %d) : %.2fn", i, *(balance + i)
);
return 0;
}
8
Output:
Array values using
pointer
*(p + 0) : 1000.00
*(p + 1) :50000.00
printf( "Array values using pointern");*(p + 2) : 300.40
Array values using balance as
address
printf("*(p + %d) : %.2fn", i, *(p + i) );*(balance + 0) : 1000.00
*(balance + 1) :
50000.00
*(balance + 2) : 300.40
Example Program:
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;
}
9
Pointer Arithmetic
The following Arithmetic operations can be performed on
10
pointer variable vPtr
v[0] v[1] v[2] v[3] v[4]
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
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
11
Pointer
Expression
How it is evaluated ?
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
ip-- or --ip ip => ip - 1 => 1020 - 1*4 => 1016
12
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 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
cp-- or --cp cp => cp - 1 => 3005 - 1*1 => 3004
Pointer Arithmetic on characters
13
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
#include<stdio.h>
int main() {
int i1 = 12, *ip1 =
&i1;
int i2 = 12, *ip2 =
&i2;
printf("Value of ip1 or address of i1 = %un", ip1);
printf("Value of ip2 or address of i2 = %unn", ip2);
printf("ip2 - ip1 = %dn", ip2 – ip1);
printf("ip1 - ip2 = %dn", ip1 – ip2);
return 0;
}
Output:
Value of ip1 or address of i1 = 2686780
Value
of ip2 or address of i2 =
2686788 ip2 - ip1 = 2
ip1 - ip2 = -2
14
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.
Syntax:
datatype **pointer_name;
Simple program to represent Pointer to a Pointer
#include <stdio.h>
int main()
{ int a =
10;
int *p1;
//pointer
variable
int **p2;
//pointer
to a
pointer
p1 = &a;
//store the
address of
variable a
p2 =
&p1; ;
//store the
Output:
Address of a = 2686724
Address of p1 = 2686728
Address of p2 = 2686732
Value at the address stored
by p2 = 2686724
Value at the address stored
by p1 = 10
Value of **p2 = 10
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
15
Pointers and Strings
 We can create a two dimensional array and save multiple
strings in it.
Example: In the below code, we are storing 4 cities name in a
string array city.
char city[4][12] = { "Chennai", "Kolkata", "Mumbai", "New
Delhi" };
Memory representation of the city array is as follows:
16
The problem with this approach is that we are allocating 4x12 = 48
bytes memory to the city array and we are only using 33 bytes.
We can save those unused memory spaces by using pointers as
shown below.
char *cityPtr[4] = { "Chennai", "Kolkata", "Mumbai", "New
Delhi" };
Memory representation of the pointer cityPtr is as follows:
17
The above array of pointers can be represented in
memory as follows.
18
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;
arrop[0] = &a;
arrop[1] = &b;
arrop[2] = &c;
for(i = 0; i < 3;
i++)
printf("Address = %dt Value = %dn", arrop[i], *arrop[i]);
return 0;
} 19
Output:
Address =
387130656
Address =
387130660
Address =
387130664
Value =
10
Value =
20
Value =
50
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.
20
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.
 To access data in dynamic memory; therefore, we must use a
pointer.
21
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 NU LL 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)); 22
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().
Syntax: free(ptr);
23
free(ptr);
return 0;
}
24
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 = (char
*)malloc(20*size
of(char));//or
ptr =
calloc(20,sizeof(
char));
strcpy(ptr, "Problem solving");
printf("ptr : %sn",ptr);
/*below statement extends the
previous block size to 100 bytes
and
return starting address*/
ptr : Problem solving
ptr : Programming for problem solving
 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.
25
PR E -PRO C E SS O R COMMANDS :
Examples
1. #define MAX_ARRAY_LENGTH 20
 This directive tells the CPP to replace instances of the macro
MAX_ARRAY_LENGTH with 20.
 A macro is a segment of code which is replaced by the value of
macro. Macro is defined by #define directive. 26
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.
27
Example program for #define, #include preprocessors in C
language:
#include <stdio.h>
#define HEIGHT 100
#define NUMBER 3.14
#define LETTER 'A'
#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);
}
28
Output:
value of HEIGHt : 100
value of NUMBER : 3.140000
value of LETTER : A
value of LETTER_SEQUENCE :
ABC
Example program for #undef in C language:
 This directive undefines existing macro in the program.
#include <stdio.h>
#define HEIGHT 100
void main()
{
printf("First defined value for HEIG HT :
%dn",HEIGHT);
#undef HEIGHT
#define HEIGHT 600
/
/ undefining variable
/
/ redefining new value
printf(“Value of HEIGHT after undef :%d",HEIGHT);
} 29
Output:
First defined value for height : 100
Value of height after undef : 600
Example program for #if, #else 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
int main()
{
#if (a==100)
printf(“a is equal to 100n");
#else
printf(“a is not equal to 100n");
#endif
return 0;
}
30
Output:
a is equal to 100
Example program for #ifdef 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
int main()
{
#ifdef RAJU
printf("RAJU is defined. n");
#else
printf("RAJU is not definedn");
#endif
return 0;
}
31
Output:
RAJ U is defined.
Example program for #ifndef 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 RAJ U 100
int main()
{
#ifndef J O H N
{
printf(“JOHN is not defined. So, now we are going to define
heren");
#define J O H N 300
}
#else
printf(“JOHN is already defined in the program”);
#endif
return 0;
}
32
Output:
J O H N is not defined. So, now we are going to
define here
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.
33
Example program on pre-defined macros
#include <stdio.h>
int main() {
printf("File :%sn", FILE );
printf("Date :%sn", DATE
);
printf("Time :%sn", TIME
);
printf("Line :%dn", LINE
); return 0;
}
Output:
File :test.c
Date :Apr 19 2021
Time :10:36:24
Line :8
34

PPSC Unit-3 POINTERS.pptx FOR STUDY PURP

  • 1.
  • 2.
    POINTER S : 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  A pointer is a variable which holds an address of some other variable. The value of a pointer variable gets stored in another memory location. 2
  • 3.
    Advantages of usingpointers:  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. Disadvantages of Pointers:  Pointers are a little complex to understand.  Pointers can lead to various errors such as segmentation faults or can access a memory location which is not required at all.  If an incorrect value is provided to a pointer, it may cause memory corruption.  Pointers are also responsible for memory leakage.  Programmers find it very difficult to work with the pointers; therefore it is programmer's responsibility to manipulate a pointer carefully. 3
  • 4.
    Declaring a Pointervariable  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; char *cp; // pointer to double variable / / pointer to char variable 4
  • 5.
    Initializing a Pointervariable  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; ptr = &a; //pointer declaration //pointer initialization Note: Pointer variable should always point to variables of same datatype. Eg: float a; int *ptr; ptr = &a; // ERR O R, type mismatch. 5
  • 6.
    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); printf("%d", *&a); printf("%u", &a); printf("%u", p); printf("%u", &p); //this will print the value of 'a' //this will also print the value of 'a' //this will print the address of 'a' //this will also print the address of 'a' //this will print the address of 'p' 6
  • 7.
    Pointer to anArray  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. 7
  • 8.
    #include <stdio.h> int main() { /* an array with 3 elements */ double balance[3] = {1000.0, 50000.0, 300.4}; double *p; int i; p = balance; /* output each array element's value */ for ( i = 0; i < 3; i++ ) printf( "Array values using balance as addressn"); for ( i = 0; i < 3; i++ ) printf("*(balance + %d) : %.2fn", i, *(balance + i) ); return 0; } 8 Output: Array values using pointer *(p + 0) : 1000.00 *(p + 1) :50000.00 printf( "Array values using pointern");*(p + 2) : 300.40 Array values using balance as address printf("*(p + %d) : %.2fn", i, *(p + i) );*(balance + 0) : 1000.00 *(balance + 1) : 50000.00 *(balance + 2) : 300.40 Example Program:
  • 9.
    Pointer Compatibility  Therules 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; } 9
  • 10.
    Pointer Arithmetic The followingArithmetic operations can be performed on 10 pointer variable vPtr v[0] v[1] v[2] v[3] v[4] 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
  • 11.
    Let's take somemore 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 11 Pointer Expression How it is evaluated ? 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 ip-- or --ip ip => ip - 1 => 1020 - 1*4 => 1016
  • 12.
    12 Pointer Arithmetic ondouble 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 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 cp-- or --cp cp => cp - 1 => 3005 - 1*1 => 3004 Pointer Arithmetic on characters
  • 13.
    13 Subtraction between twopointers  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 #include<stdio.h> int main() { int i1 = 12, *ip1 = &i1; int i2 = 12, *ip2 = &i2; printf("Value of ip1 or address of i1 = %un", ip1); printf("Value of ip2 or address of i2 = %unn", ip2); printf("ip2 - ip1 = %dn", ip2 – ip1); printf("ip1 - ip2 = %dn", ip1 – ip2); return 0; } Output: Value of ip1 or address of i1 = 2686780 Value of ip2 or address of i2 = 2686788 ip2 - ip1 = 2 ip1 - ip2 = -2
  • 14.
    14 Pointer to aPointer (Double Pointer)  When one pointer variable stores the address of another pointer variable, it is known as Pointer to Pointer variable or Double Pointer. Syntax: datatype **pointer_name; Simple program to represent Pointer to a Pointer #include <stdio.h> int main() { int a = 10; int *p1; //pointer variable int **p2; //pointer to a pointer p1 = &a; //store the address of variable a p2 = &p1; ; //store the Output: Address of a = 2686724 Address of p1 = 2686728 Address of p2 = 2686732 Value at the address stored by p2 = 2686724 Value at the address stored by p1 = 10 Value of **p2 = 10
  • 15.
    Pointers and Two-DimensionalArrays:  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 15
  • 16.
    Pointers and Strings We can create a two dimensional array and save multiple strings in it. Example: In the below code, we are storing 4 cities name in a string array city. char city[4][12] = { "Chennai", "Kolkata", "Mumbai", "New Delhi" }; Memory representation of the city array is as follows: 16 The problem with this approach is that we are allocating 4x12 = 48 bytes memory to the city array and we are only using 33 bytes.
  • 17.
    We can savethose unused memory spaces by using pointers as shown below. char *cityPtr[4] = { "Chennai", "Kolkata", "Mumbai", "New Delhi" }; Memory representation of the pointer cityPtr is as follows: 17
  • 18.
    The above arrayof pointers can be represented in memory as follows. 18
  • 19.
    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; arrop[0] = &a; arrop[1] = &b; arrop[2] = &c; for(i = 0; i < 3; i++) printf("Address = %dt Value = %dn", arrop[i], *arrop[i]); return 0; } 19 Output: Address = 387130656 Address = 387130660 Address = 387130664 Value = 10 Value = 20 Value = 50
  • 20.
    Memory Allocation:  Cgives 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. 20
  • 21.
    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.  To access data in dynamic memory; therefore, we must use a pointer. 21
  • 22.
    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 NU LL 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)); 22
  • 23.
    2. Contiguous MemoryAllocation– 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(). Syntax: free(ptr); 23
  • 24.
    free(ptr); return 0; } 24 Example programfor 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 = (char *)malloc(20*size of(char));//or ptr = calloc(20,sizeof( char)); strcpy(ptr, "Problem solving"); printf("ptr : %sn",ptr); /*below statement extends the previous block size to 100 bytes and return starting address*/ ptr : Problem solving ptr : Programming for problem solving
  • 25.
     The Cpreprocessor 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. 25 PR E -PRO C E SS O R COMMANDS :
  • 26.
    Examples 1. #define MAX_ARRAY_LENGTH20  This directive tells the CPP to replace instances of the macro MAX_ARRAY_LENGTH with 20.  A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. 26
  • 27.
    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. 27
  • 28.
    Example program for#define, #include preprocessors in C language: #include <stdio.h> #define HEIGHT 100 #define NUMBER 3.14 #define LETTER 'A' #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); } 28 Output: value of HEIGHt : 100 value of NUMBER : 3.140000 value of LETTER : A value of LETTER_SEQUENCE : ABC
  • 29.
    Example program for#undef in C language:  This directive undefines existing macro in the program. #include <stdio.h> #define HEIGHT 100 void main() { printf("First defined value for HEIG HT : %dn",HEIGHT); #undef HEIGHT #define HEIGHT 600 / / undefining variable / / redefining new value printf(“Value of HEIGHT after undef :%d",HEIGHT); } 29 Output: First defined value for height : 100 Value of height after undef : 600
  • 30.
    Example program for#if, #else 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 int main() { #if (a==100) printf(“a is equal to 100n"); #else printf(“a is not equal to 100n"); #endif return 0; } 30 Output: a is equal to 100
  • 31.
    Example program for#ifdef 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 int main() { #ifdef RAJU printf("RAJU is defined. n"); #else printf("RAJU is not definedn"); #endif return 0; } 31 Output: RAJ U is defined.
  • 32.
    Example program for#ifndef 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 RAJ U 100 int main() { #ifndef J O H N { printf(“JOHN is not defined. So, now we are going to define heren"); #define J O H N 300 } #else printf(“JOHN is already defined in the program”); #endif return 0; } 32 Output: J O H N is not defined. So, now we are going to define here
  • 33.
    Predefined Macros  Thepreprocessor 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. 33
  • 34.
    Example program onpre-defined macros #include <stdio.h> int main() { printf("File :%sn", FILE ); printf("Date :%sn", DATE ); printf("Time :%sn", TIME ); printf("Line :%dn", LINE ); return 0; } Output: File :test.c Date :Apr 19 2021 Time :10:36:24 Line :8 34