Module 5
Module 5
Module 5
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.
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.
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.
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
#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.
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
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
#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.
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
//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)
www.vtuupdates.com Page 5
C Programming for problem solving 18CPS13
Char 1
Long 4
Float 4
Double 8
long double 10
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
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
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"
};
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);
}
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;
--------------
--------------
};
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;
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:
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( )
{
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.
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
www.vtuupdates.com Page 15
C Programming for problem solving 18CPS13
VECTOR v, *ptr;
ptr = &v;
The identifier ptr is known as pointer that has been assigned the address of the structure
variable n.
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
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
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
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
www.vtuupdates.com Page 21