0% found this document useful (0 votes)
37 views21 pages

PPSC Unit IV (18-1-23)

The document discusses pointers in C programming. Some key points: 1. A pointer stores the address of another variable. Pointers allow dynamic memory allocation at runtime. 2. Pointer syntax uses an asterisk, such as int *ptr, to indicate the variable is a pointer. Normal variables store values, pointers store addresses. 3. Pointer arithmetic allows incrementing, decrementing, adding, subtracting pointers. Pointer expressions access memory locations. 4. Double pointers are pointers that point to other pointer variables. They require two asterisks like int **ptr to dereference the value. 5. Only certain expressions are lvalues that can be assigned to, while rvalues supply values. Point

Uploaded by

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

PPSC Unit IV (18-1-23)

The document discusses pointers in C programming. Some key points: 1. A pointer stores the address of another variable. Pointers allow dynamic memory allocation at runtime. 2. Pointer syntax uses an asterisk, such as int *ptr, to indicate the variable is a pointer. Normal variables store values, pointers store addresses. 3. Pointer arithmetic allows incrementing, decrementing, adding, subtracting pointers. Pointer expressions access memory locations. 4. Double pointers are pointers that point to other pointer variables. They require two asterisks like int **ptr to dereference the value. 5. Only certain expressions are lvalues that can be assigned to, while rvalues supply values. Point

Uploaded by

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

Programming for Problem Solving using C (R20)

UNIT-4
POINTERS
POINTER: A pointer is a variable that stores/points the address of another variable. A Pointer in C is
used toallocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of
the data type such as int, float, char, double, short etc.
Pointer Syntax : data_type *var_name;
Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.

Key Points to Remember about Pointers in C:


• Normal variable stores the value whereas pointer variable stores the address of the variable.
• The content of the C pointer always be a whole number i.e. address.
• Always C pointer is initialized to null, i.e. int *p = null.
• The value of null pointer is 0.
• & symbol is used to get the address of the variable.
• * symbol is used to get the value of the variable that the pointer is Pointing to.
• If a pointer in C is assigned to NULL, it means it is pointing to nothing.
• Two pointers can be subtracted to know how many elements are availablebetween these two
pointers.
• But, Pointer addition, multiplication, division are not allowed.
• The size of any pointer is 2 byte (for 16 bit compiler).

EXAMPLE PROGRAM FOR POINTER:


#include <stdio.h>
int main()
{
int *ptr, q;q = 50;
/* address of q is assigned to ptr */ptr = &q;
/* display q's value using ptr variable */printf("%d", *ptr);
return 0;
}
output: 50

A pointer to a pointer: A pointer to a pointer is a form of multiple indirection, or a chain of pointers.


Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that contains the actual
value as shown below. A variable that is a pointer to a pointer must be declared as such. This is done by
placing an additional asterisk in front of its name.
For example, the following declaration declares a pointer to a pointer of type int − int **var; When a
target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the
asterisk operator be applied twice, as is shown below

Pragati Engineering College (Autonomous) Page 1


Programming for Problem Solving using C (R20)

Example 2:
#include <stdio.h>
int main ()
{
int var; int *ptr;
int **pptr; var = 3000; // take the address of var
ptr = &var; // take the address of ptr using address of operator &
pptr = &ptr; // take the value using pptr
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
Output: Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000

Example 3:
#include<stdio.h>
void main ()
{
int a = 10;
int *p;
int **pp;
p = &a; // pointer p is pointing to the address of a
pp= &p; // pointer pp is a double pointer pointing to the address of pointer p
printf ("address of a: %x\n",p); // Address of a will be printed
printf("address of p: %x\n",pp); // Address of p will be printed
printf("value stored at p: %d\n",*p); // value stored at the address contained by p i.e. 10 will be
printed
printf("value stored at pp: %d\n",**pp); // value stored at the address contained by the pointer
stored at pp
}
Output : address of a: d26a8734address of a: d26a8734
Value is 10 address of p: d26a8738
value stored at p: 10
value stored at pp: 10

Pointer Compatibility:
//single Pointer with multiple variables
#include<stdio.h>
int main()
{

Pragati Engineering College (Autonomous) Page 2


Programming for Problem Solving using C (R20)

int a,b,c,*p; //a,b and c are variables and p is a pointerprintf("Enter three integers : ");
scanf("%d %d %d",&a,&b,&c);
p = &a;
printf("pointer points to a. Value is %d\n",*p);
p = &b;
printf("pointer points to b. Value is %d\n",*p);
p = &c;
printf("pointer points to c. Value is %d\n",*p);
return 0;
}
Output:
Enter three integers : 10
20
30
pointer points to a. Value is 10
pointer points to b. Value is 20
pointer points to c. Value is 30
//single variable with multiple Pointers
#include<stdio.h>
int main()
{
a,*p,*q,*r; //a,b and c are variables and p is a pointer
printf("Enter a integer: ");
scanf("%d",&a);
p = &a;
printf("pointer points to a. Value is %d\n",*p);
q = &a;
printf("pointer points to b. Value is %d\n",*q);
r = &a;
printf("pointer points to c. Value is %d\n",*r);
return 0;
}
Output:
Enter a integer: 10
pointer points to a. Value is 10
pointer points to b. Value is 10

Lvalue and R Value: In C, an expression is either lvalue or anrvalue. every expression has a value.
But the value in an expression can be used in two different ways.
1. An lvalue expression must be used whenever the object is receiving a value.
2. An rvalue expression can be used to supply a value for further use.

Pragati Engineering College (Autonomous) Page 3


Programming for Problem Solving using C (R20)

Only 7 types of expressions are Lvalue expressions, they are given in below table

S.No Expression Type Comments


1 Identifier Variable Identifier
2 Expression[...] Array Indexing
3 (Expression) Expression must already be lvalue
4 *Expression Dereferenced expression
5 Expre s s ion. name Structure selection
6 Expression^ name Structure indirect selection
7 Function call If function uses return by address
e.g :lvalue expressions:
 a=…
 a[5]=…
 (a)=…
 *P=…
e.g : rvalue expressions
 5
 a+2
 a*6
 a[2]+3
 a++

Only 6 operators need an lvalue expression as an operand. They are


Type of Expression Examples
Address operator &score
Postfix increment/decrement x++ y--
Prefix increment/decrement ++x --y
Assignment(left operand) x=1 y+=3

Pointer applications:
 It is a strong relationship between pointers and arrays, strong enough that pointers and arrays should
be discussed simultaneously. Any operation that can be achieved by array subscripting can also be
done with pointers.
 The declaration int a[10]; defines an array of size 10, that is, a block of 10 consecutive objects
named a[0], a[1], ...,a[9]. The notation a[i] refers to the ith element of the array. If pa is a pointer to
an integer, declared as int *pa; then theassignment
pa = &a[0]; sets pa to point to element zero of a; that is, pa contains the address of a[0].
 pa = &a[0]; pa and a have identical values. Since the name of an array is a synonym for the location
of the initial element, the assignment pa=&a[0] can also be written as In evaluating a[i], C converts
it to *(a+i) immediately; the two forms are equivalent.
 Applying the operator & to both parts of this equivalence, it follows that &a[i] and a+i are also
identical: a+i is the address of the ith element beyond a. As the other side of this coin, if pa is a
pointer, expressions might use it with a subscript; pa[i] is identical to
*(pa+i). In short, an array-and-index expression is equivalent to one written as a pointer and offset

Pragati Engineering College (Autonomous) Page 4


Programming for Problem Solving using C (R20)

C Program - Pointer Arithmetic


#include <stdio.h>int main()
{
int x[5] = {1, 2, 3, 4, 5};
int* ptr;
printf("*ptr = %d \n", *ptr); // 3
printf("*(ptr+1 = %d\n"*(ptr+1));
printf("*(ptr-1) = %d",*(ptr-1));
return 0;
}
Output: *ptr = 3
*(ptr+1) = 4
*(ptr-1) = 2

C Pointer Arithmetic: Pointer Expressions: (Address Arithmetic / Pointer Arithmetic)


In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable.
Following arithmetic operations are possible on pointer in C language:
Performing arithmetic operations using pointer variables is said to be arithmetic pointer.
1. increment
2. decrement
3. addition
4. subtraction
5. comparision
#include <stdio.h>
int main()
{
int a,b;
int *ptr, *ptr1;
ptr = &a;
ptr1 = &b;
printf("sum is : %d /n",*ptr+b);
printf("Subtraction of two pointers : %d \n", a-*ptr1);
return 0;
}
Output: sum of two pointers : 16
subtraction of two pointers : 4

Incrementing Pointer variable : To display the value stored in an array without using any index value.
Then Pointer will help you toget there by using increment operator.

Example: Increment pointer.c


#include <stdio.h>
int main()
{
int arr[3] = {10, 11, 12};
int *ptr, i;
ptr = arr;

Pragati Engineering College (Autonomous) Page 5


Programming for Problem Solving using C (R20)

for(i = 0; i< 3; i++)


{
printf("%d\t", *ptr);
ptr++;
}
return 0;
}

Output: 10 11 12

Decrementing Pointer Variable: Like increment, we can decrement a pointer variable. The formula of
decrementing pointer is given below:
new_address= current_address - i * size_of(data type)

Program - Decrementing Pointer variable Decrement pointer.c


#include <stdio.h>
int main()
{
int a[3] = {10, 11, 12};
int *ptr, i; ptr = &a[2];
for(i = 3; i> 0; i--)
{
printf("%d\t", *ptr);
ptr--;
}
return 0;
}
Output: 12 11 10

Comparing Pointer Variable: Pointer variable can be compared either with other pointer variable or
with normal variable. Relational operators will get you there for comparison operation. Let us using
greater than operatorto compare two pointer variables.

Program Comparing Pointer variable


#include <stdio.h>
int main()
{
int a = 10, b = 6;
int *ptr, *ptr1; ptr = a;
ptr1 = &b;
if(*ptr> *ptr1)
printf("value stored in a is greater than b ");
else
printf("value stored in b is greater than a ");
return 0;
}
Output: value stored in a is greater than b

Dynamic Memory Allocation: The concept of dynamic memory allocation in C language

Pragati Engineering College (Autonomous) Page 6


Programming for Problem Solving using C (R20)

enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language
is possible by 4 functions of stdlib.h header file.
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory allocation
and dynamic memory allocation.

S.No Static Memory Allocation Dynamic Memory Allocation


1 Memory is allocated at compile time Memory is allocated at run time.
Memory can't be increased while Memory can be increased while
2
executing program executing program
3 Used in array. Used in linked list.

Methods used for Dynamic Memory Allocation.

malloc() Allocates single block of requested memory.


calloc() Allocates multiple block of requested memory.
realloc() Reallocates the memory occupied by malloc() or calloc() functions.
free() Frees the dynamically allocated memory.

1. malloc(): The malloc() function allocates single block of requested memory in bytes. It doesn't initialize
memory at execution time, so it has garbage value initially.Itreturns NULL if memory is not sufficient.

Syntax: ptr=(cast-type*)malloc(byte-size);
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr,sum=0;
printf("Elements of array: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using mallocif(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("\nEnter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("\nSum=%d",sum); free(ptr);

Pragati Engineering College (Autonomous) Page 7


Programming for Problem Solving using C (R20)

return 0;
}
Output:
Elements of array: 3 Enter
elements of array: 21
3
Sum=6
calloc(): The calloc() function allocates multiple block of requested memory. It initially initialize all
bytes to zero. It returns NULL if memory is not sufficient.

Syntax: ptr=(cast-type*)calloc(number, byte-size);


#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr,sum=0; printf("Elements of array: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc if(ptr==NULL)
{
printf("Sorry! unable to allocate
memory");exit(0);
}
printf("\nEnter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("\nSum%d",sum);
free(ptr);
return 0;
}
Output:
Elements of array: 3 Enter
elements of array: 21
3
Sum=6

realloc(): If memory is not sufficient for malloc() or calloc(), you can reallocate the memory byrealloc()
function. In short, it changes the memory size.

Syntax: ptr=realloc(ptr, new-size);

Example:
#include<stdio.h>
#include<stdlib.h>
int main()
{

Pragati Engineering College (Autonomous) Page 8


Programming for Problem Solving using C (R20)

int *p, i, n;
printf("Initial size of the array is 4\n\n");p
= (int*)calloc(4, sizeof(int));
if(p==NULL)
{
printf("Memory allocation failed");
exit(1); // exit the program
}
for(i = 0; i< 4; i++)
{
printf("Enter element at index %d: ", i);
Final array: scanf("%d", p+i);
}
printf("\nIncreasing the size of the array by 5 elements ...\n ");
p = (int*)realloc(p, 9 * sizeof(int));
if(p==NULL)
{
printf("Memory allocation failed");exit(1); // exit the program
}
printf("\nEnter 5 more integers\n\n");
for(i = 4; i< 9; i++)
{
printf("Enter element at index %d:
", i);scanf("%d", p+i);
}
printf("\nFinal array: \n\n");
for(i = 0; i< 9; i++)
{
printf("%d ", *(p+i) );
}
// signal to operating system program ran fine
return 0;
}
Output:
Enter element at index 0: 11
Enter element at index 1: 33
Enter element at index 2: 22
Enter element at index 3: 55
Increasing the size of the array by 5 elements ...
Enter 5 more integers
Enter element at index 4: 99
Enter element at index 5: 77
Enter element at index 6: 88
Enter element at index 7: 66
Enter element at index 8: 44
11 33 22 55 99 77 88 66 44

Pragati Engineering College (Autonomous) Page 9


Programming for Problem Solving using C (R20)

Example 2:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int)*2);
int i;
int *ptr_new;
*ptr = 10;
*(ptr + 1) = 20;
ptr_new = (int *)realloc(ptr, sizeof(int)*3);
*(ptr_new + 2) = 30;
for(i = 0; i< 3; i++) printf("%d ", *(ptr_new + i));
return 0;
}
Output:
10 20 30

4. free(): free () function frees the allocated memory by malloc (), calloc (), realloc () functions and
returns the memory to the system.
Syntax: free(ptr);
Array of pointers: “Array of pointers” is an array of the pointer variables. It is also known as pointer
arrays.
Syntax: int*var_name[array_size];
Declaration of an array of pointers: int *ptr[3];

We can make separate pointer variables which can point to the different values or we can make one
integer array of pointers that can point to all the values.

// C program to demonstrate array of pointers.


#include <stdio.h>
const int SIZE = 3;
void main()
{
int arr[] = { 1, 2, 3 };
int i, *ptr[SIZE];
for (i = 0; i< SIZE; i++)
{
ptr[i] = &arr[i]; // assigning the address of integer.
}
for (i = 0; i< SIZE; i++)
{
printf("Value of arr[%d] = %d\n", i, *ptr[i]); // prints values using pointer
}
}
Output:
Value of arr[0] = 1
Value of arr[1] = 2
Value of arr[2] = 3

Pragati Engineering College (Autonomous) Page 10


Programming for Problem Solving using C (R20)

Example for finding array element address:


#include<stdio.h>
main()
{
int marks[4] = {89, 45, 58, 72} ;
int i;
for(i = 0; i<4 ; ++i)
printf("Address of 'marks[%d]' = %d\n", i, &marks[i]) ;
}
Output:
Address of 'marks[0]' = 6487552
Address of 'marks[1]' = 6487556
Address of 'marks[2]' = 6487560
Address of 'marks[3]' = 6487564

Example for finding array element value:


#include <stdio.h>
int main()
{
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i< 6; ++i)
{
scanf("%d",(classes + i)); // (classes + i) is equivalent to &classes[i]
sum+= *(classes + i); // *(classes + i) is equivalent to classes[i]
}
printf("Sum = %d", sum);return 0;
}
Output: Enter 6 numbers:
2
3
1
4
5
9
Sum = 24
Another example for calculating sum of array elements with pointers:
#include <stdio.h>
int main()
{
int data[5], i;
printf("Enter elements: ");
for(i = 0; i< 5; ++i)
scanf("%d", data + i);
printf("You entered: \n");
for(i = 0; i< 5; ++i)
printf("%d\n", *(data + i));
return 0;

Pragati Engineering College (Autonomous) Page 11


Programming for Problem Solving using C (R20)

}
Output:
Enter elements: 3
4
2
6
1
You entered:
3
4
2
6

ARRAYS OF STRINGS WITH POINTERS:


#include <stdio.h>
const int MAX = 4;
int main ()
{
char *names[] = { "c", "c++", "python", "java" };
int i = 0;
for ( i = 0; i< MAX; i++)
{
printf("Value of names[%d] = %s\n", i, names[i]);
}
return 0;
}
Output:
Value of names[0] = c Value
of names[1] = c++ Value of
names[2] = pythonValue of
names[3] = java

Types of Pointers : There are four different types of pointers which are as follows −
 Null pointer
 Void pointer
 Wild pointer
 Dangling pointer

Null Pointer: A Null Pointer is a pointer that does not point to any memory location. It stores the base
address of the segment. The null pointer basically stores the Null value while void is the type of the
pointer. This method is useful when you do not assign any address to the pointer. A null pointer
always contains value 0.
//Example Program
#include <stdio.h>
int main()
{
int *ptr = NULL; //null pointer
printf("The value inside variable ptr is:%d",ptr);
return 0;
}
Output:

Pragati Engineering College (Autonomous) Page 12


Programming for Problem Solving using C (R20)

The value inside variable ptr is: 0

Void Pointer: It is a pointer that has no associated data type with it. A void pointer can hold addresses
of any type and can be typecast to any type. It is also called a generic pointer and does not have any
standard data type. It is created by using the keyword void.
\
// C program for the void pointer
#include <stdio.h>
int main()
{
void *p = NULL; //void pointer
printf("The size of pointer is:%d",sizeof(p)); //size of p depends on compiler
return 0;
}
Output:
The size of pointer is: 8

Wild Pointer: Pointers store the memory addresses. Wild pointers are different from pointers i.e. they
also store the memory addresses but point the unallocated memory or data value which has been
deallocated. Such pointers are known as wild pointers.
//Example:
#include <stdio.h>
int main()
{
int *p; //wild pointer
printf("%d",*p);
return 0;
}
Output:
Process returned -1073741819 (0xC0000005) execution time : 1.206 s
In the above program, a pointer arr is declared but not initialized. So, it is displaying some random
memory locations.

Dangling pointer: Dangling pointer is a pointer pointing to a memory location that has been freed (or
deleted). Thereare different ways where Pointer acts as dangling pointer.
//Example
#include <stdio.h>
int main()
{
int *show(void)
{
int n = 76; /* ... */ return &n;
}
Output: Output of this program will be garbage address.

Pragati Engineering College (Autonomous) Page 13


Programming for Problem Solving using C (R20)

De-allocation of memory
#include <stdio.h>
int main()
{
float *p = (float *)malloc(sizeof(float)); //dynamic memory allocation.
free(p); //after calling free()
//p becomes a dangling pointer
p = NULL; //now p no more a dangling pointer.
}
Variable goes out of scope:
#include <stdio.h>
int main()
{
int *p //some code/
{
int c;
p=&c;
}
//some code
//p is dangling pointer here.
}
Preprocessor Directives: Before a C program is compiled in a compiler, source code is processed by a
program calledpreprocessor. This process is called preprocessing. Commands used in preprocessor are
called preprocessor directives. They are never terminated with a semicolon(;).

 It is placed before the main().


 In C programming language, preprocessor directive is a step performed before the actualsource
code compilation. It is not part of the compilation.
 When we try to compile a program, preprocessor commands are executed first and then the
program gets compiled.
 Every preprocessor command begins with # symbol. We can also create preprocessorcommands
with parameters.
Following are the preprocessor commands in C programming language.
#define: #define is used to create symbolic constants (known as macros) in C programming language.
Thispreprocessor command can also be used with parameterized macros.
//macro example :
#include<stdio.h>
#define LOWER 5
void main()
{
int i;
for (i=1;i<=LOWER; i++)
printf("\n%d", i); //displays 1 to 5 numbers
}
Output:

Pragati Engineering College (Autonomous) Page 14


Programming for Problem Solving using C (R20)

1
2
3
4
5

Macro with parameters Example:


#include<stdio.h>
#define AREA(a) (3.14 * a * a)
int main()
{
float r = 1.5, x; x = AREA (r); printf
("\n Area of circle = %f", x);return 0;
}
Output: Area of circle = 7.065000

Some Preprocessor Directives


Preprocessor
S.No. Description
Command
1 #undef used to destroy a macro that was already created using #define.
returns TRUE if the macro is defined and returns FALSE if the macro is not
2 #ifdef
defined.
3 #ifndef returns TRUE if the specified macro is not defined otherwise returns FALSE.
4 #if uses the value of specified macro for conditional compilation.
5 #else is an alternative for #if.
6 #elif is a #else followed by #if in one statement.
7 #endif is used terminate preprocessor conditional macro.
8 #include is used to insert specific header file into C program.
9 #error used to print error message on stderr.
10 #program used to issue a special command to the compiler.

In C programming language, there are some pre-defined macros and are


Preprocessor
S.No. Description
Command
1 DATE The current date as characters in "MMM DD YYYY" format.
2 TIME The current time as characters in "HH : MM : SS" format.
3 FILE This contains the current file name.
4 LINE This contains the current line number.
5 STDC Defines 1 when compiler compiles with ANSI Standards.
PREPROCESSORS:
S.No. Macro Description
This macro defines constant value and can be any of the basic data
1 #define
types.
The source code of the file “file_name” is included in the main
2 #include <file_name>
C programwhere “#include <file_name>” is mentioned.

Pragati Engineering College (Autonomous) Page 15


Programming for Problem Solving using C (R20)

// Example program for #include:


#include<stdio.h>
int main()
{
printf("Hello C");
return 0;
}
Output: Hello C

#define example 1:
#include <stdio.h>
#define PI 3.14
main()
{
printf("%f",PI);
}
Output: 3.140000

//Example 2
#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A' void
main()
{
printf("value of height : %d \n", height);
printf("value of number : %f \n", number);
printf("value of letter : %c \n", letter);
}
Output: value of height: 100
value of number: 3.140000
value of letter: A

CONDITIONAL COMPILATION DIRECTIVES: #IFDEF, #ELSE AND #ENDIF


“#ifdef”: directive checks whether particular macro is defined or not. 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. So, this line will be added in " \"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0;
}
Output: RAJU is defined. So, this line will be added in this C file

Pragati Engineering College (Autonomous) Page 16


Programming for Problem Solving using C (R20)

#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.
//Example Program
#include<stdio.h>
#define RAJU 100int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \"define there\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program”);#endif
return 0;
}
OUTPUT: SELVA is not defined. So, now we are going to define here

FOR #IF, #ELSE AND #ENDIF: “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.
//Example Program
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added = 100\n");#else
printf("This line will be added is not equal to 100\n");
#endif
return 0;
}
OUTPUT:
This line will be added in this C file since a = 100
//Example on #else
#include <stdio.h>
#include <conio.h>
#define NUMBER 1
void main()
{
#if NUMBER==0
printf("Value of Number is: %d", NUMBER);
#else
printf("Value of Number is non-zero");
#endif
getch();
}

Pragati Engineering College (Autonomous) Page 17


Programming for Problem Solving using C (R20)

Output:
Value of Number is non-zero
UNDEF : This directive undefines existing macro in the program.
//Example for #undefine
#include <stdio.h>
#define PI 3.14
#undef PI
main()
{
printf("%f",PI);
}
Output : Compile Time Error: 'PI' undeclared

//Example 2:
#include <stdio.h>
#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 undef \& redefine:%d",height);
}
OUTPUT: First defined value for height : 100
value of height after undef& redefine : 600

Example 3:
#include <stdio.h>
#define number 15
int square=number*number;
#undef number
main()
{
printf("%d",square);
}
Output: 225

//Example Program to call a function before and after main function in a C program.
#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 );
printf("STDC :%d\n",STDC );
return 0;
}
Output: File :program examle.c

Pragati Engineering College (Autonomous) Page 18


Programming for Problem Solving using C (R20)

Date :Apr 16 2021


Time :05:43:28
Line :6
STDC :1

Example 2:
#include <stdio.h>
void function1( );
void function2( );
#program startup function1
#program exit function2
int main( )
{
printf ( "\n Now we are in main function" ) ;
return 0;
void function1( )
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called after main function call”);
}
}
Output: Function1 is called before main function call
//Now we are in main function
Function2 is called just before end of main function

Pragati Engineering College (Autonomous) Page 19


Programming for Problem Solving using C (R20)

Exercise Programs
1. Program to create, initialize, assign and access a pointer variable.
2. Program to swap two numbers using pointers.
3. Program to change the value of constant integer using pointers.
4. Program to print a string using pointer.
5. Program to count vowels and consonants in a string using pointer.
6. Program to read array elements and print with addresses.
7. Program to read and print student details using structure pointer, demonstrate example of structure
with pointer.
8. Program to print size of different types of pointer variables.
9. Program to demonstrate example of double pointer (pointer to pointer).
10. Program to demonstrate example of array of pointers.
11. An Example of Null pointer in C
12. Making a valid pointer as NULL pointer in C
13. Modify value stored in other variable using pointer in C

UNIT IV PREVIOUS QUESTIONS


1) What is pointer? Explain how the pointer variable declared and initialized?
2) What are the memory allocation functions C?
3) Write a program using pointers to swap two numbers.
4) Differentiate malloc and calloc?
5) What is pointer? give the advantages and disadvantages of pointer data type
6) What is difference between malloc and calloc?
7) Explain the array of pointers with example.
8) Explain the following Dynamic Memory Allocation functions in C malloc (), calloc (), free() and
realloc ()
9) What is address arithmetic in C? Explain different arithmetic operations that can be
performed on pointers.
10) Write a program to convert floating point number into integer using pointers
11) Write the syntax and explain the concepts of pointers, declaring pointer variables and null
pointers
12) Write a C program that access elements of one Dimensional array using a pointer variable
13) What is a pointer? How do you declare and use pointers?
14) Explain array of pointers with an example
15) Write a C program using pointers to compute the sum of all elements stored in an arrayusing
pointers.
16) Explain about pointer to pointer with an example.
17) Write a C program to read a string using a character pointer and also to display it.
18) List Dynamic Memory Allocation functions and explain any two with suitableexamples.
19) List and explain the valid operations that are performed on pointers.
20) Define pointer. Explain how to declare and use pointers.

Pragati Engineering College (Autonomous) Page 20


Programming for Problem Solving using C (R20)

Assignment 4
Q.No. Questions BTL CO

SET - 1
1 What is pointer? Explain how the pointer variable declared and initialized? K2 CO4
Explain the following Dynamic Memory Allocation functions in C malloc(),
2 K2 CO4
calloc(), free() and realloc()
3 Write a program using pointers to swap two numbers. K3 CO4
SET - 2
1 Explain about pointer to pointer with an example K2 CO4
2 List and explain the valid operations that are performed on pointers. K2 CO4
3 Write a C program using pointers to add two numbers using pointers. K3 CO4
SET - 3
1 Define pointer. Explain how to declare and use pointers. K2 CO4
2 Differentiate malloc and calloc with suitable example. K2 CO4
Write a C program that access elements of one Dimensional arrayusing a
3 K3 CO4
pointer variable.

Pragati Engineering College (Autonomous) Page 21

You might also like