Module 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

C Programming for problem solving 18CPS13

Module -5
POINTER, STRUCTURES AND PREPROCESSORS

Pointers: A pointer is a variable that holds the address of another variable. The pointer variable
contains only the address of the referenced variable not the value stored at that address.

Some of the advantages of using pointers are as follows


1. Pointers are more efficient in handling arrays and data tables
2. Pointers are used with function to return multiple values
3. Pointers allow C to support dynamic memory management
4. Pointers provide an efficient tool for manipulating dynamic data structures such as
structures, linked list, stacks, queues, trees etc
5. Pointers reduce length and complexity of program
6. Pointers reduce program execution time and saves data storage space in memory

Disadvantages of pointers
1. One of the disadvantage of using pointer is that program may crash if sufficient memory
is not available at run time to store pointers.

Pointer uses two basic operators


1. The address operator (&): It gives address of an object
2. The indirection operator (*):It is used to accesses the object the pointer points to.

Declaring a pointer variable:


The general syntax of declaring pointer variable is

Datatype *ptrname;

-Data type: It specifies the type of the pointer variable that you want to declare like (int, float,
char, double or void)
* (Asterisk): tells the compiler that you are creating a pointer variable and ptrname specifies the
name of the pointer variable.

Example: int *p; // declares a pointer variable p of integer type


float *temp;// declares a pointer variable temp of float data type

Initialization of pointer variable: Similar to the initialization of other variables at the time of
their declaration, you can also initialize the pointer variable by assigning address of other variables
to them.
Syntax
Datatype *ptrname = expression;

www.vtuupdates.com Page 1
C Programming for problem solving 18CPS13

Where
Datatype: It can be any basic data type,
ptrname is a pointer variable
expression can be any constant value or any variable containing value.
Example:
Example 1:
int a;
int *ptr = &a; //address of a is stored in ptr variable .
Example 2:
float temp; // temp is a variable of float type
float *p; //p is a ptr variable pointing to float type
p=&temp; // pointer variable p holds the address of temp

Program to illustrate declaration and initialization

#include<stdio.h>
void main()
{
int *ptr; / /declaration of pointer variable
int a=10;
ptr=&a; / /initialization of pointer variable
printf(“the value of a=%d\”,a);
printf(“the value of a using pointer=%d\n”,*ptr);
printf(“the address of a=%u\n”,ptr);
}
Output:
The value of a=10
The value of a using pointer=10
The address of a =32200

Using the address of (&) operator: A computer uses memory to store the instructions of different
programs and the values of different variables. Since memory is a sequential collection of storage
cells, each cell has an address. When you declare a variable, the operating system allocates
memory according to the size of the data type of that variable. In this memory location, the value
of the variable is stored.

Example : int a=100;

This statement request the operating system to allocate two bytes of space in memory and stores
100 in that location.

www.vtuupdates.com Page 2
C Programming for problem solving 18CPS13

a -------------- variable name

100 --- --------- value of the variable

1500 ------------- the address of the memory location

By using the address of (&) operator, you can determine the address of a variable.

#include<stdio.h>
void main()
{
a=100,*ptr1; float
b=12.6, *ptr2;
ptr1=&a;
ptr2=&b;
printf(“the address of a = %u and its value is%d\n”,ptr1,*ptr1);
printf(“the address of b =%u and its value is %f
%f\n”,ptr2,*ptr2);
getch();
}
Output: The address of a=2600 and its value is 100
The address of b=4876 and its value is 12.600000

Pointers and functions (call by reference) arguments:


The call by reference method allows you to copy the addresses of actual arguments of the calling
function to the formal arguments of the called function. In this method the pointers are passed as
arguments to the functions.
ctions. When you change the values in the functions, the original values of
the actual parameters are also changed. Following program illustrate use of call by reference.

#include<stdio.h>
void swap(int *a, int *b);
void main()
{
int x,y; x=100; y=200;
printf(“before swap: x=%d\nn y=%d
y=%d\n”x,y);
swap(&x,&y);
printf(“after swap: x=%d\n,y=%d
n,y=%d\n”,x,y);
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;

www.vtuupdates.com Page 3
C Programming for problem solving 18CPS13

Output:
Before swap: x=100
y=200
After swap: x=200
y=100
Pointers and arrays: Arrays are closely related to pointers in C programming but the
important difference between them is that, a pointer variable can take different addresses as
value whereas, in case of array it is fixed. This can be demonstrated by an example:

#include <stdio.h>
void main()
{
char c[4];
int i;
for(i=0;i<4;++i)
{
printf("Address of c[%d]=%x\n",i,&c[i]);
}
}
Notice, that there is equal difference (difference of 1 byte) between any two consecutive
elements of array.

Note: You may get different address of an array.


Relation between Arrays and Pointers

Consider and array:

int arr[4];

In arrays of C programming, name of the array always points to the first element of an array.
Here, address of first element of an array is &arr[0]. Also, arr represents the address of the
pointer where it is pointing. Hence, &arr[0] is equivalent to arr.
Address in arrays Address in pointes Value in arrays Value in pointers
&a[0] (a+0) a[0] *(a+0)

www.vtuupdates.com Page 4
C Programming for problem solving 18CPS13

&a[1] (a+1) a[1] *(a+1)


&a[2] (a+2) a[2] *(a+2)
&a[3] (a+3) a[3] *(a+3)
&a[4] (a+4) a[4] *(a+4)
……. ………. …….. ………
&a[i] (a+i) a[i] *(a+i)

//C Program to find the sum of 10 marks with arrays and pointers.
#include <stdio.h>

void main()
{
int i,marks[10],sum=0;
printf("Enter 10 marks:\n");
for(i=0;i<10;++i)
scanf("%d",(marks+i));
for(i=0;i<10;++i){
sum += *(marks+i);
}
printf("Sum=%d",sum);
getch();
}
Output
Enter 10 marks:
2 3 4 5 3 5 7 10 21 28
Sum=88

Pointer Arithmetic
Pointer arithmetic is very important to understand, if you want to have complete knowledge of
pointer. In this topic we will study how the memory addresses change when you increment a
pointer.

16 bit Machine
In a 16 bit machine, size of all types of pointer, be it int*, float*, char* or double* is always 2
bytes. But when we perform any arithmetic function like increment on a pointer, changes occur as
per the size of their primitive data type.
Type Size(bytes)

int or signed int 2

www.vtuupdates.com Page 5
C Programming for problem solving 18CPS13

Char 1

Long 4

Float 4

Double 8

long double 10

Examples for Pointer Arithmetic

Now lets take a few examples and understand this more clearly.

int* i;
i++;
In the above case, pointer will be of 2 bytes. And when we increment it, it will increment by 2
bytes because int is also of 2 bytes.

float* i;
i++;
In this case, size of pointer is still 2 bytes. But now, when we increment it, it will increment by 4
bytes because float is of 4 bytes.

double* i;
i++;
Similarly, in this case, size of pointer is still 2 bytes. But now, when we increment it, it will
increment by 8 bytes because its data type is double.

Pointers to 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

www.vtuupdates.com Page 6
C Programming for problem solving 18CPS13

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 in the example –

#include <stdio.h>

void main ()
{
int var; int *ptr;
int **pptr; var = 3000;
ptr = &var;
pptr = &ptr;
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
getch();
}
Output:
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000

Pointer and Character strings


Pointer can also be used to create strings. Pointer variables of char type are treated as string. char
*str = "Hello";
This creates a string and stores its address in the pointer variable str. The pointer str now points
www.vtuupdates.com Page 7
C Programming for problem solving 18CPS13

to the first character of the string "Hello". Another important thing to note that string created using
char pointer can be assigned a value at runtime.
char *str;
str = "hello";
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to
use indirection operator * .
Array of Pointers
We can also have array of pointers. Pointers are very helpful in handling character array with
rows of varying length.
Consider the following array of strings
char name[3][25]; //name is a table containing three names of maximum length 25(including null
character. Total storage is 75 bytes.
We may encounter rarely all the individual strings of length equal to 25. Therefore instead
of making each row fixed number of characters, we can make it a pointer to a string of varying
length. For example
char *name[3]={
"Bangalore",
"Chennai",
"Mangalore"
};
Declares name to be an array of three pointers to character, each pointer pointing to a particular
name as
Name[0] --------- Bangalore
Name[1] ---------Chennai
Name [2] -------- Mangalore
This declaration allocates only 28 bytes, sufficient to hold all characters. Whereas using array of
strings , same array without using pointer needs 75 bytes.
char name[3][25]= {
"Bangalore",
"Chennai",
"Mangalore"
};

Initialization of Pointer Arrays


Consider the problem of writing a function month_name(n), which returns a pointer to a character
string containing the name of the n-th month. This is an ideal application for an internal static

www.vtuupdates.com Page 8
C Programming for problem solving 18CPS13

array. month_name contains a private array of character strings, and returns a pointer to the proper
one when called. This section shows how that array of names is initialized.
/* month_name: return name of n-th month */
char *month_name(int n)
{
static char *name[] = {
"Illegal month",
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
};
return (n < 1 || n > 12) ? name[0] : name[n];
}
The declaration of name, which is an array of character pointers, The initializer is a list of character
strings; each is assigned to the corresponding position in the array. The characters of the i-th string
are placed somewhere, and a pointer to them is stored in name[i]. Since the size of the array name
is not specified, the compiler counts the initializers and fills in the correct number.
Function returning Pointer
A function can also return a pointer to the calling function. In this case you must be careful,
because local variables of function doesn't live outside the function, hence if you return a pointer
connected to a local variable, that pointer be will pointing to nothing when function ends.
#include <stdio.h>
#include <conio.h>
int* larger(int*, int*);
void main()
{
int a=15; int b=92; int *p;
p=larger(&a, &b);
printf("%d is larger",*p);
}

int* larger(int *x, int *y)


{
if(*x > *y)
return x;
else
return y;
}
www.vtuupdates.com Page 9
C Programming for problem solving 18CPS13

STRUCTURES

INTRODUCTION
C supports a constructed data type known as structures, a mechanism for packing data of different
data types. A structure is a convenient tool for handling a group of logically related data items.
For example: it represents set of attributes such as student_name, roll_no, marks.

DEFINING A STRUCTURE
Structures must be defined first for their format that may be used later to declare structure
variables. Consider a book database consisting of book name, author, number of pages and price.
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
The keyword struct declares a structures to hold details of four fields, namely title, author,
Pages and price. These fields are called structure elements or structure members. book_bank is
called structure tag.
The general format of structure definition is as follows

struct tag_name

datatype member1;

datatype member2;

--------------

--------------

};

In defining structure you may note the following syntax


1. The template is terminated with a semicolon
2. while the entire definition is considered as a statement, each member is declared
independently for its name and type in a separate statement inside the template.
3. The tag_name such as book_bank can be used to declare structure variables of its type.

www.vtuupdates.com Page 10
C Programming for problem solving 18CPS13

ARRAYS VS STRUCTURES
Sl.no Arrays Structures
1 Array is a collection of related data Structure is collection of logically related
elements data elements of different data types.
of same data type
2 Array is derived data type Structure is a programmer-defined one.
3 Array behaves like built in data type In case of Structures, first we have to design
and declare a data structure.
4 In Arrays we have to declare an array In structures after designing structure and
variables and use it. declaring then we can declare structure
variables and use it.
DECLARING STRUCTURE VARIABLES
After defining a structure format we have declare variables of that type. A Structure variable
declaration is similar to the declaration of variables of any other data types.
It includes the following elements.
1. The keyword struct.
2. The structure tag name.
3. List of variable names separated by commas.
4. A terminating semicolon.
For example
struct book_bank book1, book2, book3;

declares book1, book2 and book3 as variables of type struct book_bank.

The complete declaration look like

OR it can also be done like given below

struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
}book1, book2, book3;

www.vtuupdates.com Page 11
C Programming for problem solving 18CPS13

Type-defined structures
We can use the keyword typedef to define a structure as follows:
typedef struct
{
--------------
type member1;
type member2;
--------------
--------------
}type_name;

The type_name represents structure definition associated with it and therefore, can be used
to declare structure variables as shown below:

type_name variable1, variable2, .................... ;

ACCESSING STRUCTURE MEMBERS


The members of structures can be in different ways. One way is by use of Dot operator or period
operator such as ‘ . ’
For example
book1.price
the link between a member and variable is established using dot operator.
Examples:
1. book1.pages=250;
2. book1.price=120.00;

STRUCTURE INITIALIZATION
Like any other data type, a structure can be initialized at compile time.

www.vtuupdates.com Page 12
C Programming for problem solving 18CPS13

main( )
{
struct st_record
{
int weight;
float height;
};
struct st_record student1={ 60, 180.75};
struct st_record student1={ 53, 170.60};
………….
………….
}

Another method is to initialize a structure variables outside the function as shown below:
struct st_record
{
int weight; float
height;
student1={ 60, 180.75};
}

main( )
{

struct st_record student 2={ 53, 170.60};


………….
………….
}

www.vtuupdates.com Page 13
C Programming for problem solving 18CPS13

C language does not permit initialization of individual structure members within the template. The
initialization must be done only in the declaration of actual variables.
NOTE: The compile time initialization of a structure variable must have the following elements.
1. The keyword struct.
2. The structure tag name.
3. The name of the variable to be declared.
4. The assignment operator =.
5. The set of values for the members of the structure variables, separated by commas and
enclosed in braces.
6. A terminating semicolon.
Rules For Initializing Structures
There are few rules to be remembered while initializing structure variables at compile time
1. We cannot initialize individual members inside the structure template
2. The order of values enclosed in braces must match the order of members in the structure
definition.
3. It is permitted to have a partial initialization. We can initialize only the first few members and
leave the remaining blank. The uninitialized members should be only at the end of the list.
4. The uninitialized members will be assigned default values as follows
 Zero for integer and floating point numbers.
 ‘\0’ for character and strings.

COPYING AND COMPARING STRUCTURE VARIABLES


Two variables of the same structure type can be copied the same way as ordinary variables. If person1
and person2 belong to the same structure, then the following statements are valid:
person1=person2;
person2=person1;
However, the statements such as
person1 = = person2;
person2 != person1;
are not permitted(not valid or invalid) because C does not permit any logical operations on
structure variables. In case, we need to compare them, we may do so by comparing members
individually.

The following program illustrates how a structure variable can be copied into another of the same
type. It also performs member wise comparsion to decide whether two structure variables are
identical.

www.vtuupdates.com Page 14
C Programming for problem solving 18CPS13

Program
struct class
{
int number;
char name[20]; float marks;
};

main( )
{
int x;
struct class student1={ 111, “Rao”, 72.50};
struct class student2={ 222, “Reddy”, 67.00}; struct class student3;

student3 = student2;
x=( (student3. number = = student2. number) && (student3.marks = = student2.marks) )
? 1: 0 ;

if(x = = 1)
{
printf(“\n student2 and student3 are same\n\n”);
printf(“%d %s %f\n”, student3.number, student3.name, student3.marks);
}
else
printf(“\n student2 and student3 are different\n\n”);
}
Output
student2 and student3 are same

222 Reddy 67.000000

Figure Comparing and copying structure variables

www.vtuupdates.com Page 15
C Programming for problem solving 18CPS13

OPERATIONS ON INDIVIDUAL MEMBERS


The individual members are identified using the member operator, the dot. A member with
the dot operator along with its structures variable can be treated like any other variables name and
therefore can be manipulated using expressions and operators.
Consider the above program, we can perform the following operations:
if(student1.number = = 111)
student1.marks = student1.marks + 10.00;
float sum = student1.marks + student2.marks;
student2.marks = student2.marks * 0.5;
we can also apply increment and decrement operators to numeric type members.
For example: student1.number ++;
++ student1.number;
The precedence of the member operator is higher than all arithmetic and relational
operators and therefore no parenthesis are required.
THREE WAYS TO ACCESS MEMBERS
We have used the dot operator to access the members of structures variables. In fact, there are two
other ways.
Consider the following structure:
typedef struct
{
int x; int y;
} VECTOR;

VECTOR v, *ptr;
ptr = &v;
The identifier ptr is known as pointer that has been assigned the address of the structure
variable n.

Now, the members can be accessed in the following three ways:

ARRAYS OF STRUCTURES
We use structures to describe the format of a number of related variables. For example analyzing
the marks obtained by a class of students, we may use template to describe student name and marks
obtained in various subjects and then declare all the students as structure variables.
In such cases, we may declare an array of structures, each element of the array representing a
structure variable.

www.vtuupdates.com Page 16
C Programming for problem solving 18CPS13

For example: struct class student[100];


defines an array called student, that consists of 100 elements. Each element is defined to be of
the type struct class.
Consider the following declaration:
struct marks
{
int sub1;
int sub2;
int sub3;
};
main( )
{
struct marks student[3] = { {45, 68, 81},{75, 53, 69},{57, 36, 71}};
}

This declares the student as an array of three elements student[0], student[1] and student[2]
and initialize their members as follows:
student[0].sub1=45; student[0].sub2=68;
……..
……..
student[2].sub3=71;
Note: Each element of student array is a structure variable with three members.

An array of structures is stored inside the memory in the same way as a multi dimensional array.
The array student actually looks as shown below

www.vtuupdates.com Page 17
C Programming for problem solving 18CPS13

Program
struct marks
{
int sub1;
int sub2;
int sub3;
}; int T;
main( )
{
int i;
struct marks student[3] = {{45, 68, 81,0},{75, 53, 69,0},{57, 36, 71,0}};
struct marks total;
for( i = 0; i<=2; i++)
{
student[i].T= student[i].sub1+ student[i].sub2+ student[i].sub3;
total.sub1= total.sub1 + st udent[i].sub1;
total.sub2= total.sub2 + student[i].sub2;
total.sub3= total.sub3 + student[i].sub3;
total.T= total.T + student[i].T;
}
Printf(“STUDENT TOTAL\n\n ”);
for( i = 0; i<=2; i++)
printf(“student[%d]%d\n”,i+1, student[i].T );
printf(“\n SUBJECT\t\tTOTAL\n\n”);
printf(“%s\t\t%d\n”, “SUB JECT1”, total.sub1);
printf(“%s\t\t%d\n”, “SUB JECT2”, total.sub2);
printf(“%s\t\t%d\n”, “SUBJECT3”, total.sub3);
printf(“\n GRAND TOTAL = %d\n”, total.T);
}
OUTPUT
STUDENT TOTAL
student[1] 193
student[2] 197
student[3] 164
SUBJECT TOTAL
SUBJECT1 177
SUBJECT2 156
SUBJECT3 221
GRAND TOTAL = 554

www.vtuupdates.com Page 18
C Programming for problem solving 18CPS13

C Pre-processor directives

 Before a C program is compiled in a compiler, source code is processed by a program


called preprocessor. This process is called preprocessing.
 Commands used in preprocessor are called preprocessor directives and they begin with
“#” symbol.
 Below is the list of preprocessor directives that C language offers.

Sl.no Preprocessor Syntax Description


1 Macro #define This macro defines constant value and can be any
of the basic data types.
2 Header file #include The source code of the file “file_name” is included
inclusion <file_name> in the main program at the specified place
3 Conditional #ifdef, #endif, #if, Set of commands are included or excluded in
compilation #else, #ifndef source program before compilation with respect to
the condition
4 Other #undef, #pragma #undef is used to undefine a defined macro
directives variable. #Pragma is used to call a function before
and after main function in a C program

The directives listed above are categorized into 3 types


1. The macro substitution directive
2. The file inclusion directives
3. Compiler control directives
Macro substitution: Macro substitution is a process where an identifier in a program is
replaced by a predefined string composed of one or more tokens. The preprocessor
accomplishes this task under the direction of #define statement. It takes the following form
#define identifier string
Here the preprocessor replaces every occurrence of the identifier in the source code by the
string.
Example:
#define PI 3.14
#define COUNT 100
Macros with arguments: The preprocessor permits us to define more complex and more
useful form of replacements. It takes the form
#define identifier(f1,f2…fn) string.
The following statement appears later in the program
Volume=CUBE(side);
Then the preprocessor would expand (side*side*side)

Nesting of macros: we can also use one macro in the another macro. That is macro
definition may be nested Example #define M 5
#define N M+1
#define SQUARE(x) ((x)*(x))

www.vtuupdates.com Page 19
C Programming for problem solving 18CPS13

#define CUBE(X) SQUARE((x)*(x))

File inclusion: An external file containing functions or macro definition can be included
as a part of program so that we need not rewrite those functions or macro definition. This
is achieved by preprocessor directive.
#include “filename”
Where filename is the name of the file containing the required file. When the filename
is included within the double quotation marks, the search for the file is made in first in
the current directory and then in the standard directory.
Alternatively
#include<filename>
In this case file is searched only in the standard directories
Example:
#include<stdio.h>
void main()
{
clrscr();
}
include a header file or define a macro under a specified condition. The compiler control
directives are as follows
1. #ifdef
2. #ifndef
3. #if
4. #ifelse
5. #ifelif
Conditional compilation: the compiler compiles selected porstion of the source codes based
on the condition.
Syntax of #ifdef directive is
#ifdef<identifier>
{
Statement 2;
}
#else
{
Statement 3;
Statement 4;

www.vtuupdates.com Page 20
C Programming for problem solving 18CPS13

}
#endif
The #ifdef preprocessor test whether the identifier has defined substitute text or not. If the
identifier is defined then #if block is compiler and executed. If the identifier is not defined,
the #else block is compiled and executed.
{
#ifdef LINE
printf(“this is line number1\n”);
#else
printf(“this is line number2\n”);
#endif
}
Output : This is line number 1

The #ifndef Directive


Syntax of #ifndef directive is
#ifndef<identifier>
{
Statement 1;
}
#else
{
Statement 3;
Statement 4;
}
#endif
The #ifndef preprocessor test whether the identifier has defined substitute text or not.
If the identifier is defined then #else block is compiler and executed. If the identifier is
not defined, the #if block is compiled and executed
Example program
#ifndef LINE
printf(“this is line number 1\n”);
#else
Printf(“this is line number2\n”);
#endif
}
Output: This is line number2

www.vtuupdates.com Page 21

You might also like