CP Unit-4 R19
CP Unit-4 R19
Pointers
Pointers
Generally computer uses memory for storing instruction and values of the variables which we are
using in the program, but the pointers have memory address as their values. The memory address
is the location where program instructions and data are stored; pointers can be used to access and
manipulate data stored in the memory.
Example : int sno=39; above statement instructs the system to specify a location for the integer
variable 'sno' and put the value 39 in that location. Assume that the system has chosen the
address location 65542 for sno this may be represented as
sno
39
65542
sno - Variable
39 - Value
65542 - Address
Pointer Concept:
"A pointer is a variable, it may contain the memory address of another variable." Pointer can
have any name that is legal for other variable. It is declared in the same manner like other
variables. It is always denoted by '*' operator.
Pointer Declaration:
Pointer is a variable that contain the address of another variable. Like normal variable declared in
'C' pointers can also be declared.
Syntax data-type *pointer-name;
Description data-type Specifies the type of data to which the pointer points.
Pointer-name Specifies the name of the pointer. (It must preceded with an (*) asterisk.
Example: int *a; *a mean 'a' contains the address of variable, which is integer variable.
char *b; *b mean 'b' contain the address of variable, which is character variable.
float *c; *c means 'c' contain the address of variable, which is float variable.
RIET,CSE Page 1
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
RIET,CSE Page 2
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
value. On incrementing, a pointer will point to the memory location after skipping N bytes,
where N is the size of the data type(in this case it is 4).
ptr++ is equivalent to ptr + (sizeof(pointer_data_type)).
"Incrementing a pointer increases its value by the number of bytes of its data type"
A character(1 bytes) pointer on increment jumps 1 bytes.
An integer(4 bytes) pointer on increment jumps 4 bytes.
This is a very important feature of pointer arithmetic operations which we will use in array
traversal using pointers.
Decrementing a Pointer
Similarly, Decrementing a pointer will decrease its value by the number of bytes of its data type.
Hence, after
ptr--;
ptr will point to 4996.
ptr--; is equivalent to ptr - (sizeof(pointer_data_type)).
Adding Numbers to Pointers
Adding a number N to a pointer leads the pointer to a new location after skipping N times size of
data type.
ptr + N = ptr + (N * sizeof(pointer_data_ype))
For example, Let ptr be a 4-byte integer pointer, initially pointing to location 5000.
Then ptr + 5 = 5000 + 4*5 = 5020. Pointer ptr will now point at memory address 5020.
Subtracting Numbers from Pointers
Subtracting a number N from a pointers is similar to adding a number except in Subtraction the
new location will be before current location by N times size of data type.
ptr - N = ptr - (N * sizeof(pointer_data_ype))
For example, Let ptr be a 6-byte double pointer, initially pointing to location 5000.
Then ptr - 3 = 5000 - 6*3 = 4982. Pointer ptr will now point at memory address 4982.
Subtracting Pointers
We can take difference between two pointer which returns the number of bytes between the
address pointed by both the pointers.
For example, if a pointer 'ptr1' points at memory location 10000 and pointer 'ptr' points at
memory location 10008, the result of ptr2 - ptr1 is 8.
RIET,CSE Page 3
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
If any pointer is pointing the memory address of any variable but after some variable has deleted
from that memory location while pointer is still pointing such memory location. Such pointer is
known as dangling pointer and such memory is known as dangling memory. In short pointer
pointing to non-existing memory location is called dangling pointer.
Initially: Later:
Null Pointer:
A pointer is said to be a null pointer when its right value is 0. A null pointer can never point to a
valid data. For checking a pointer, if it is assigned to 0, then it is a null pointer and is not valid.
Example : int *a;
int *b;
b=a=0;
Hence b and a become null pointers after the integer value of 0 is assigned to them.
Pointer to Pointer: Pointer is a variable that contains the address of another variable. Similarly
another pointer variable can store the address of this pointer variable. So we can say, this is a
pointer to pointer variable.
Compatibility
• Pointers have a type associated with them, such as char, int, float, etc.
• Each pointer takes on the attributes of the type to which it refers to in addition to its own
attributes.
• Compatibility types are:
a) Pointer Size Compatibility
b) Dereference Type Compatibility
c) Dereference Level Compatibility
RIET,CSE Page 5
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
Example:
Casting Pointers
• The problem of type incompatibility can be solved by using casting.
• An explicit assignment between incompatible pointer types is done by using a cast
operator.
• For example,
• pc=(char *)&a; /*pc is a character pointer and a is a integer pointer */
• This converts an integer pointer to a char and assigns the value to pc.
RIET,CSE Page 6
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
R-value: r-value” refers to data value that is stored at some address in memory. A r-value is an
expression that can’t have a value assigned to it which means r-value can appear on right but not
on left hand side of an assignment operator(=).
RIET,CSE Page 7
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
p = &b;
struct S { int m; };
Remembering the mnemonic, that lvalues can appear on the left of an assignment operator
while rvalues can appear on the right.
int x, y;
RIET,CSE Page 8
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
Pointer and Functions: The pointer can be used as arguments in functions. The arguments or
parameters to the function are passed in two ways.
i) Call by value
ii) Call by reference
Call By Value: The process of passing the actual value of variables is known as "call by value".
When a function is called in program, the values to the arguments in the function are taken by
the calling program; the value taken can be used inside the function. Alteration to the value is not
accepted inside the function in calling program but change is locally available in the function.
Example : /*Write a program to swap (interchange) the two given variable.*/
#include<stdio.h>
main ( )
{
int a=10, b=20;
printf ("\n Before swap a=%d,b=%d",a,b); //10, 20
void swap(a,b);
printf ("\n After the calling the swap function, a=%d,b=%d", swap(a,b); //10, 20
}
void swap(x,y)
int x,y;
{
x=x+ y;
y=x-y;
x=x-y;
printf ("In swap function x=%d,y=%d",x,y); //20, 10
}
Call By Reference: The process of calling a function using pointers to pass the addresses of
variables is known as "call by reference". A function can be declared with pointers as its
arguments. Such function is called by calling program with the address of a variable as argument
from it.
Example : /* Program to explain about call by reference */
#include<stdio.h>
main ( )
{
int a=10, b=20;
RIET,CSE Page 9
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
void change(x,y)
int x,y;
{
x=x + 5;
y=y + 10;
printf ("In the function changes a&b is %d,%d",*x,*y); //15, 30
}
Pointer and Arrays: Array is a collection of similar data type elements stored under common
name. When we declare an array the consecutive memory locations are located to the array of
elements. The elements of an array can be efficiently accessed by using pointers.
Example : /* Program to add the sum of number using pointer * /
#include<stdio.h>
main( )
{
int b, total;
int a[5];
int * c;
for (b=0;b<5;b++ )
{
printf ("Enter the number%d” , b+1); //10 20 30 40 50
scanf ("%d",&a[b]);
}
c=a;
for (b=0;b<5;b++ )
{
printf ("%d",* c);
total=total + * c;
c = c + 1;
}
printf ("\n Total=%d", total); //150
}
RIET,CSE Page 10
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
Example : /* Program to print the value and address of the element using array of pointers */
#include<stdio.h>
main( )
{
int *a[3]; /* *a[3] is a pointer variable */
int b=10, c=20, d=30, i;
a[0]=&b;
a[1]=&c;
a[2]=&d;
for (i=0; i<3; i++)
{
printf ("Address=%u",a[i]);
printf ("Value=%d",*(a[i]));
}
}
RIET,CSE Page 11
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
FUNCTION MEANING
malloc() Used to allocate blocks of memory in required size of bytes.
free() Used to release previously allocated memory space.
calloc() Used to allocate memory space for an array of elements
realloc() Used to modify the size of the previously allocated memory space.
malloc() function: The malloc() function is used to allocate block of memory (i.e.) it allocates a
block of memory of specified size and return a pointer of type void. It takes the following form-
Ptr=(data_type*)malloc(byte_size);
int *p;
p=(int *)malloc(5*(sizeof (int));
1024 >
calloc()function: The calloc() function is used for allocating memory space during the program
execution for derived data types such as arrays, structures etc. It takes the following form-
RIET,CSE Page 12
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
Ptr=(data_type*)calloc(n, byte_size);
int *p;
p=(int *)calloc(10*(sizeof (int));
free(p);
P 1024 1026
free() function: The free() function is used to release the previously allocated memory space
using malloc() or calloc() i.e., it is the opposite of malloc() function. It takes the following form-
Syntax void free(void *p);
int *p;
p=(int *)malloc(5*(sizeof (int));
free(p);
realloc() function: It is necessary to alter the previously allocated memory. i.e.,to add additional
memory or to reduce as and when required.
For above purposes, the realloc() function is very useful and this process is called reallocation of
memory.
Before using this statement, the user must allocate some memory previously by using the
malloc() function.
new_ptr=(data_type*)realloc(old_ptr, new_size);
int *p;
p=(int *)malloc(10* sizeof(int));
p=(int *)realloc(p,10));
Malloc realloc
#include<stdio.h> #include<stdio.h>
#include<malloc.h> #include<malloc.h>
void main() #include<string.h>
{ void main()
int *ptr, n, i; {
printf("ENter no. of elements"); char *name;
scanf("%d", &n); //4 name=(char *)malloc(12,sizeof(char));
iptr=(int *) malloc(n*sizeof(int)); strcpy(name, "VaniCollege");
printf(Enter %d elements\n" n); printf("Name %s at address %d", name,name);
for(i=0;i<n;i++) name=(char *)realloc(name, 15*sizeof(char));
scanf("%d",iptr+1); //10,20.30.40 strcpy(name, "VahiniCollege");
printf("The list of the elements\n"); printf("Name %s is at address %d\n", name, name);
for(i=0;i<n;i++) free(name);
printf("%d\n", &(iptr+1)); getch();
free(iptr); }
}
RIET,CSE Page 13
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
RIET,CSE Page 14
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
To sum up, preprocessing directives occurs before program compilation. So, it can be also be
referred to as pre compiled fragments of code.
Some possible actions
1. File Inclusion
2. Macros
3. Conditional Compilation
4. Other directives
.
All preprocessor directives has begin with the # operator.
1. File inclusion
The file inclusion uses the #include.
Syntax:
#include filename
The content that is included in the filename will be replaced at the point where the
directive is written.
By using the file inclusive directive, we can include the header files in the programs.
Macros, function declarations, declaration of the external variables can all be combined
in the header file instead of repeating them in each of the program.
The stdio.h header file contains the function declarations and all the information
regarding the input and output.
There are two ways of the file inclusion statement:
i) #include “file-name”
ii) #include <file-name>
If the first way is used, the file and then the filename in the current working directory and
the specified list of directories would be searched.
If the second way, is used the file and then the filename in the specified list of directories
would be searched.
2.Macro Definition or #define Preprocessor Directive
The #define preprocessor directive for symbolic constants :
• Used to create symbolic constants with the format
#define identifier replacement-text
• Enables the programmer to create a name for the constant and use that name throughout
the program, making the program self-documenting
RIET,CSE Page 15
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
#include <stdio.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
void main() {
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}
O/P: Minimum between 10 and 20 is: 1
RIET,CSE Page 16
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
Some of the predefined macros which are readily available are as follows:
Macro Description
3.Conditional Compilation:
Conditional Compilation directives are type of directives which helps to compile a specific
portion of the program or to skip compilation of some specific part of the program based on
some conditions.
#ifdef: The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it
executes the code otherwise #else code is executed, if present.
Syntax:
#ifdef MACRO
//code
#endif
#ifdef MACRO
//successful code
RIET,CSE Page 17
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
#else
//else code
#endif
Example:
#include <stdio.h>
#include <conio.h>
#define NOINPUT
void main() {
int a=0;
#ifdef NOINPUT
a=2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}
Output:Value of a: 2
But, if you don't define NOINPUT, it will ask user to enter a number. So output of program is
Enter a:5
Value of a: 5
#ifndef: The #ifndef preprocessor directive checks if macro is not defined by #define. If yes,
it executes the code otherwise #else code is executed, if present.
Syntax :
#ifndef MACRO
//code
#endif
RIET,CSE Page 18
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
Example:
#include <stdio.h>
#include <conio.h>
#define INPUT
void main() {
int a=0;
#ifndef INPUT
a=2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}
Output:
Enter a:5
Value of a: 5
But, if you don't define INPUT, it will execute the code of #ifndef. Then output is
Value of a: 2
#if: The #if preprocessor directive evaluates the expression or condition. If condition is true,
it executes the code otherwise #elseif or #else or #endif code is executed.
#else :The #else preprocessor directive evaluates the expression or condition if condition of
#if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.
#elif : The preprocessor will include the C source code that follows the #elif statement
when the condition of the preceding #if, #ifdef or #ifndef directive evaluates to false and
the #elif condition evaluates to true.
#endif: The #endif directive closes off the following directives: #if, #ifdef, or #ifndef. When
the #endif directive is encountered
Syntax:
#if expression
//if code
#elif expression
RIET,CSE Page 19
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
//elif code
#else
//else code
#endif
Example:
#include <stdio.h>
#include <conio.h>
#define NUMBER 1
void main() {
#if NUMBER==0
printf("Value of Number is: %d",NUMBER);
#else
print("Value of Number is non-zero");
#endif
getch();
}
Output:
Value of Number is non-zero
4 Other directives:
Apart from the above directives there are some more directives which are not commonly used.
These are
1)Line control ( #line ): Whenever we compile a program, there are chances of occurrence of
some error in the program. Whenever compiler identifies error in the program it provides us with
the filename in which error is found along with the list of lines and with the exact line numbers
where the error is. This makes easy for us to find and rectify error.
However we can control what information should the compiler provide during errors in
compilation using the #line directive.
Syntax:
#line number "filename"
number – line number that will be assigned to the next code line. The line
numbers of successive lines will be increased one by one from this point on.
“filename” – optional parameter that allows to redefine the file name that will be
shown.
RIET,CSE Page 20
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
2)Error directive ( #error ): This directive aborts the compilation process when it is found in
the program during compilation and produces an error which is optional and can be specified as a
parameter.
Syntax:
#error optional_error
Here, optional_error is any error specified by the user which will be shown when this
derective is found in the program.
3)Undef directive(#undef):
This directive undefines or removes a macro name previously created with #define.
Syntax:
#undef macro_name
Here #undef is followed by macro name that has to be undefined.
Similar to definition, undefinition also occurs at the specific point in the source file, and it
applies starting from that point.
Therefore #undef directive removes the current definition of macro and all subsequent
occurrences of macro name are ignored by the preprocessor.
4) Pragma Directive(#pragma):
This directive is a special purpose directive and is used to turn on or off some features. This type
of directives are compiler-specific i.e., they vary from compiler to compiler. Some of the
#pragma directives are discussed below:
1. #pragma startup and #pragma exit: These directives helps us to specify the functions
that are needed to run before program startup( before the control passes to main()) and
just before program exit (just before the control returns from main()).
Example:
#include<stdio.h>
#include<conio.h>
void func() ;
void main(){
printf("\nI am in main");
getch();
}
RIET,CSE Page 21
PROGRAMMING FOR PROBLEM SOLVING USING C UNIT-IV
void func(){
printf("\nI am in func");
getch();
}
Directives Description
RIET,CSE Page 22