0% found this document useful (0 votes)
1 views52 pages

Module-5 POINTER Notes

This document provides an overview of pointers in the C programming language, explaining their definition, usage, and benefits. It covers key concepts such as pointer variables, initialization, dereferencing, dangling pointers, and NULL pointers, along with examples of pointer operations and their applications in arrays and functions. Additionally, it discusses the differences between passing parameters by value and by reference using pointers.
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)
1 views52 pages

Module-5 POINTER Notes

This document provides an overview of pointers in the C programming language, explaining their definition, usage, and benefits. It covers key concepts such as pointer variables, initialization, dereferencing, dangling pointers, and NULL pointers, along with examples of pointer operations and their applications in arrays and functions. Additionally, it discusses the differences between passing parameters by value and by reference using pointers.
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/ 52

CPS[18CPS13]

MODULE-5
POINTERS
Pointers are variables that hold address of another variable of same data type.
Pointers are one of the most distinct and exciting features of C language. It provides
power and flexibility to the language. Although pointer may appear little confusing
and complicated in the beginning, but trust me its a powerful tool and handy to use
once its mastered.
⮚ The basic data types in C language are int float char, double and void.
⮚ Pointer is a special data type which is derived from these data types.
⮚ So pointer is called derived data type.
The pointers are always associated with the following three concept.
● Pointer constants
● Pointer values
● Pointer variables
✔ The computer memory is divided into a number of locations called storage cells.
✔ Each location can hold one byte of information and each location is associated
with address.
✔ These memory address are called pointer constants.
✔ These memory location assigned to variable by the system are called pointer
values.
✔ A variable which holds the address of another variable is called a pointer
variable.
Example: If i is a variable and address of i is stored in a variable P
p=&i;
Then the variable p is called a Pointer variable.

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 1


CPS[18CPS13]
MODULE-5

⮚ Benefit of using pointers


● Pointers are more efficient in handling Array and Structure.
● Pointer allows references to function and thereby helps in passing of function
as arguments to other function.
● It reduces length and the program execution time.
● It allows C to support dynamic memory management.
⮚ Concept of Pointer
Whenever a variable is declared, system will allocate a location to that
variable in the memory, to hold value. This location will have its own address number.
Let us assume that system has allocated memory location 80F for a variable a. int a =
10 ;

The value 10 can be accessed by either using the variable name a or the
address 80F.Since the memory addresses are simply numbers they can be assigned to
some other variable. The variable that holds memory address are called pointer
variables. A pointer variable is therefore nothing but a variable that contains an

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 2


CPS[18CPS13]
MODULE-5
address, which is a location of another variable. Value of pointer variable will be
stored in another memory location.

⮚ Declaring a pointer variable


General syntax of pointer declaration is, data-type *pointer_name;
Data type of pointer must be same as the variable, which the pointer is
pointing. void type pointer works with all data types, but isn't used oftenly.
Pointers declaration and definition:
Pointer variables should be declared before they are used.
Syntax: type * identifier;

Example 1: int *p;


double *pd;

In the declaration, the position of * is immaterial.


Example 2: int *pa;
int * pa;
int* pa;

Example 3: int* pa,pb,pc;

int *pa; //pa is the pointer variable


int pb; //pb and pc are ordinary variable
int pc;
⮚ Initialization of Pointer variable

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 3


CPS[18CPS13]
MODULE-5
Pointer Initialization is the process of assigning address of a variable to
pointer variable. Pointer variable contains address of variable of same data type. In C
language address operator & is used to determine the address of a variable. The &
(immediately preceding a variable name) returns the address of the variable associated
with it.
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ; //initialization and declaration together
Pointer variable always points to same type of data.
float a;
int *ptr;
ptr = &a;
Example:
Declare a data variable
Ex: int x;
Declare a pointer variable
Ex: int *px;
Assign address of a data variable to pointer variable using & operator and assignment
operator.
Ex: px=&x;
OR
int x,*px=&x;

Example: int p,*ip;


float d,f;
ip = &p; /* Correct */ ip= &d; /* wrong */

⮚ Dereferencing of Pointer

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 4


CPS[18CPS13]
MODULE-5
Once a pointer has been assigned the address of a variable. To access the value
of variable, pointer is dereferenced, using the indirection operator * .
int a,*p;
a = 10;
p = &a;
printf("%d",*p); //this will print the value of a.
printf("%d",*&a); //this will also print the value of a.
printf("%u",&a); //this will print the address of a.
printf("%u",p); //this will also print the address of a.
printf("%u",&p); //this will also print the address of p.
Accessing variables through pointers

Steps to be followed while using pointers

Declare a data variable


Ex: int a;
Declare a pointer variable
Ex: int *p;
Initialize a pointer variable
Ex: p=&a;
Access data using pointer variable
Ex: printf(“%d”,*P);
⮚ Dangling Pointer
Example:
int *p;

p Garbage value

A pointer variable should contain a valid address.


A pointer variable which does not contain a valid address is called dangling pointer.
Pointers are flexible: i.e pointer can point to different data

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 5


CPS[18CPS13]
MODULE-5
Variables by storing the address of appropriate variables.
Example:
int x=10,y=20,z=30; x
Int *p;
P=&x; y
P=&y; p
P=&z;
z
⮚ NULL pointer:-
A NULL pointer is defined as a special pointer value that point to nowhere in the
memory.
Example: #include<stdio.h>
int *p=NULL
if(p==NULL) //Error condition
printf(“P does not point to any memory\n”);
else
printf(“Access the value of P\n”);

/* C program to add two number using pointers */

#include <stdio.h>
int main()
{
int num1, num2, sum;
int *ptr1, *ptr2;
ptr1 = &num1; // ptr1 stores the address of num1
ptr2 = &num2; // ptr2 stores the address of num2 printf("Enter any two numbers: ");
scanf("%d%d", ptr1, ptr2);

sum = *ptr1 + *ptr2;

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 6


CPS[18CPS13]
MODULE-5
printf("Sum = %d", sum);
return 0;
}

❖ Pointer and Arrays


When an array is declared, compiler allocates sufficient amount of memory to
contain all the elements of the array. Base address which gives location of the first
element is also allocated by the compiler.
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte,
the five element will be stored as follows in figure 6

Array Representation

Here variable arr will give the base address, which is a constant pointer pointing to
the element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
We can declare a pointer of type int to point to the array arr.
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element
to another. NOTE : You cannot decrement a pointer once incremented. p-- won't
work.
⮚ Pointer to Array
As studied above, we can use a pointer to point to an Array, and then we can use
that pointer to access the array. Lets have an example,

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 7


CPS[18CPS13]
MODULE-5
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
In the above program, the pointer *p will print all the values stored in the array one by
one.
We can also use the Base address (a in above case) to act as pointer and print all the
values.

Pointers to multidimensional array


A multidimensional array is of form, a[i][j] . Lets see how we can make a
pointer point to such an array. As we know now, name of the array gives its base
address. In a[i][j] , a will give the base address of this array, even a+0+0 will also give
the base address, that is the address of a[0][0] element. Here is the generalized form
for using pointer with multidimensional arrays.

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 8


CPS[18CPS13]
MODULE-5
*(*(ptr + i) + j)is same as a[i][j]
Algorithm 14: To compute the sum, mean and standard deviation of all elements
stored in an array of n real numbers.

Step 1: [Start]
Step 2: [Input the elements]
Read n, a[i]
Step 3: [Initialize]
sum=0, temp=0
Step 4: [Compute sum, mean, sta dev]
Ptr=a
For i=0 to n
steps of 1 sum=sum+*ptr
Ptr++
Mean=sum/n
Ptr=a
For i=0 to n in steps of 1
temp=temp+pow((*ptr-mean),2)
Ptr++
var=temp/n
std= sqrt(sumstd/n)
Step 5: [Output]
Print sum, mean, standard deviation

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 9


CPS[18CPS13]
MODULE-5
Step 6: [Stop]

Program:
#include main( )
{

int n, i;
float a[20], sum, mean, var, sd;
float *p;
printf(“Enter the value of N\n”);
scanf(“%d”, &n);
printf(“Enter the elements\n”);
for( i = 0; i < n ; i + + )
{
scanf(“%f”, &a[i] );
}
p = a; // p = &a[0];

// To find sum and mean


sum=0.0;
for( i = 0; i < n ; i + + )
{
sum = sum + *(p+i);
}
mean = sum/n;

// To find variance
temp=0.0
for( i = 0; i < n ; i + + )
{
temp = temp + (*(p+i) - mean) * (*(p+i) - mean);

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 10


CPS[18CPS13]
MODULE-5
}
var = temp/n;
/ To find standard deviation

sd = sqrt(var);

printf("sum = %f\n", sum);


printf("mean = %f\n", mean); printf("variance = %f\n", var); printf("stand dev =
%f\n", sd);

return 0;
}

Enter the value of N


6
Enter the elements
12
34
10
50
42
33
Sum of all the elements= 171
Mean of all elements = 29.66
Varience of all elements = 213.89
Standard deviation = 14.62
⮚ Pointers and functions
There are two ways of passing parameters to the functions

✔ Pass by value (also called call by value)


✔ Pass by reference (also called call by reference)

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 11


CPS[18CPS13]
MODULE-5

● Pass by value (call by value)

✔ When a function is called with actual parameters, the values of actual parameters
are copied into formal parameters.

✔ If the values of the formal parameters changes in the functions, the values of the
actual parameters are not changed.

✔ This way of passing parameters is called pass by value or call by value


C program swapping of two numbers
#include<stdio.h>
Void exchange(int m, int n);
void main()
{
int a,b;
a=10, b=20;
printf(“Before exchange”);
printf(“a=%d and b=%d\n”,a,b);
exchange(a,b);
printf(“After exchange”);
printf(“a=%d and b=%d\n”,a,b);
}
Void exchange(int m,int n)
{
int temp;
printf(“Before exchange\n”); printf(“m=%d and n=%d\n”,m,n);

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 12


CPS[18CPS13]
MODULE-5
temp=m;
m=n;
n=temp;
printf(“After exchange\n”); printf(“m=%d and n=%d\n”,m,n);
}
OUTPUT
Before exchange

a=10 and b=20

After exchange
a=10 and b=20
Before exchange
m=10 and n=20
After exchange
m=20 and n=10
● Pass by reference (call by reference)
✔ In pass by reference, a function is called with addresses of actual parameters.
✔ In the function header, the format parameters receive the addresses of actual
parameters.
✔ Now, the formal parameters do not contain values, instead they contain addresses.
✔ Any variable if it contains an address, it is called a pointer variable.
✔ Using pointer variables, the values of the actual parameters can be changed.
✔ This way of passing parameters is called Pass by reference or call by reference.
C program swapping of two numbers
#include<stdio.h>
Void exchange(int *m, int *n);

void main()
{
int a,b;

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 13


CPS[18CPS13]
MODULE-5
a=10, b=20;
printf(“Before exchange”);
printf(“a=%d and b=%d\n”,a,b);
exchange(&a,&b);
printf(“After exchange”);
printf(“a=%d and b=%d\n”,a,b);
}
Void exchange(int *m,int *n)
{
int temp;
printf(“Before exchange\n”); printf(“m=%d and n=%d\n”,m,n);
temp=m;
m=n;
n=temp;
printf(“After exchange\n”); printf(“m=%d and n=%d\n”,m,n);
}
OUTPUT
Before exchange
a=10 and b=20
After exchange
a=20 and b=10
Before exchange
m=10 and n=20
After exchange
m=20 and n=10
❖ 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 to the first character of the string "Hello". Another important thing to

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 14


CPS[18CPS13]
MODULE-5
note that string created using char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //this is Legal
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
Array of pointers can also be declared. Pointers are very helpful in handling
character array with rows of varying length.
char *name[3]={
"Adam",
"chris",
"Deniel"
};
//Now see same array without using pointer
char name[3][20]= {
"Adam", "chris",
"Deniel"
};

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 15


CPS[18CPS13]
MODULE-5

Array of pointers

The above figure shows the array of pointers used to store the character arrays.
The pointers hold the address of each of the string. Each pointer will point to the first
character of their respective strings.
❖ Pointer to a Pointer
Just as we have pointers to int, float or char, we can also have pointers to pointers.
This is because, a pointer is also a variable. Hence, we can always have another
variable (pointer) which can contain the address of the pointer variable.

EX:
int a = 10; // integer variable
int *p; // pointer to an integer
int **q; // pointer to a pointer to an integer
p = &a;
q = &p;
This is pictorially as shown below.
The above shows a 2-level indirection, however, there is no limit as to how many
levels of indirection we can use.
Here,

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 16


CPS[18CPS13]
MODULE-5

✔ p is the address of ‘a’ (2000)


✔ *p is the contents or value at address 2000 i.e. 10
✔ q is the address of p (3000)
✔ *q is the contents or value at address 3000 (2000)
✔ **q is the contents or value at address 2000 (10)
✔ a = *p = **q
⮚ Comparison of Pass by Value and Pass by Reference
Sl
n Pass by Value Pass by Reference
o.
Values of variables are passed in Addresses of the variables are passed in the
1
the function call. function call.
The type of actual and formal The type of actual and formal parameters
2 parameters must be same. must be same and the formal parameters must
be declared as pointers.
Formal parameters contain the Formal parameters contain the addresses of
3
values of actual parameters. actual parameters.
The actual parameters are not The actual parameters are changed when the
4 changed when the formal formal parameters are changed.
parameters are changed.
Less information transfer. Only More information transfer as changes made
5 one value can be returned. to formal parameters change actual
parameters.

❖ Functions returning pointers

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 17


CPS[18CPS13]
MODULE-5
✔ A function can return a single value using return statement or multiple values
using pointers in parameters.
✔ Since pointer is also a data type in C, we can return a pointer from a function.

Example:-Program to return pointer to larger of two numbers.

void main()
{
int x,y,*big;
printf(“Enter the value of x & y\n”);
scanf(“%d%d”,&x,&y);
big=largest(&x,&y);
printf(“Maximum(%d,%d)=%d\n”,x,y,*big);
}
int *largest(int *a, int *b)
{
if (*a>*b)
return a;
else
return b;
}
Compatibility and void pointer

✔ As we convert the type of one data variable into type of another data variable
using type casting.
✔ We can make an assignment between incompatible pointer types using explicit
type casting.

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 18


CPS[18CPS13]
MODULE-5

Incompatible pointer assignment Valid pointer assignment

int a; int a;
float *x float *x;
X=&a; /* error */ /* type casting a pointer */
X=(float *) &a; /*valid */

Void pointer:

✔ A void pointer is a special type of pointer.


✔ It points to any data type.
✔ Void pointer is also called universal pointer or generic pointer.

Example:
void *p;
void main()
{
int x=10;
double y=3.14156;
void *p;
p=&x;
printf(“x=%d\n”,*((int *)p));
}
✔ An object that occurs on the left hand side of assignment operator is called
L-value.
✔ Anything that occur on the right hand side of assignment statement is called
R-value.

❖ Pointer Expressions:-

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 19


CPS[18CPS13]
MODULE-5
Like other variables, pointer variables can be used in expressions.

Example:
declared and initialized pointer.
y=*p1 * *p2;
sum=sum + *p1;
z=5* - * p2/*p1;
*p2 = *p2 + 10;

Add integer to or subtract integer from pointer.


p1+4
p2-2
p1-p2
Short –hand operator with the pointers.
p1++;
--p2 ;
sum+=*p2;
Pointers can also be compared using the relational operator.
p1>p2,p1==p2 & p1!=p2

We may not use pointers in division or multiplication.


p1/p2 or p1*p2 or p1/3 are not allowed.

Two pointers cannot be added.


i.e p1+p2 is illegal.
❖ Pointers can be used to manipulate two – dimensional arrays as well .

One dimensional array x, the expression.


* (x+i) or *(p+i) = x[i]

Two dimensional array can be represented by the pointer expression as follows:

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 20


CPS[18CPS13]
MODULE-5

*(*(a+i)+j) or *(*(p+i)j)

*(*(p+i)+j)value stored in the cell (i,j)

p pointer to first row


p+i pointer to ith row
*(p+i) pointer to first element in the ith row

*(p+i)+j pointer to jth element in the ith row

Pointers and Character Strings


C supports an alternative method to create strings using pointer variables of type char.
char *str=“good”;
The pointer str now points to the first character of the string “good: as

g o o d

str
printf(“%s”, str); //puts(str);
Write a program using pointer to determine the length of a character string.
main()
{
char *name;
int length;
char *cptr = name;
name = DELHI”;
printf(“%s\n”,name);

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 21


CPS[18CPS13]
MODULE-5
while(*ctr!=‘\0’)
{
printf(“%c is stored at address %u\n”,*cptr,cptr);
cptr++;
}
length = cptr-name;
printf(“\n length of the string = %d\n”,length);
}

❖ Pointer to functions

✔ A function, like a variable, has a physical location in the memory..

✔ Like assigning address of a variable to pointer, it is possible to assign address of a


function to a pointer.

✔ Once a pointer points to a function, the function can be invoked using this pointer

✔ Using function pointer, it is possible to pass functions as parameters .

Syntax: type (*fp)();

type : type of value returns from the function


*fp is pointer to a function
Example:
#include<stdio.h>
int addition ();
int main ()
{
int result;
int (*ptr)();

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 22


CPS[18CPS13]
MODULE-5
ptr = &addition;
result = (*ptr)();
printf("The sum is %d",result);
}
int addition()
{
int a, b;
printf("Enter two numbers?");
scanf("%d %d",&a,&b);
return a+b;
}

Enter two numbers?

10 and 15

The sum is 25
❖ Pointers and Structures
✔ The name of an array stands for the address of its zeroth element.
✔ The same thing is true of the name of arrays of structure variables.
✔ Suppose product is an array variable of struct type.
✔ The name product represents the address of its zeroth element.
Consider the following declaration:
struct inventory
{
char name[30];
int number[30];
float price;
}product[2],*ptr;
ptr=product;

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 23


CPS[18CPS13]
MODULE-5
Its members can be accessed using the following
ptrname
ptrnumber
ptrprice
/*Write a program to illustrate the use of structure pointer */

struct invent
{
char name[30];
int number[30];
float price;
};

main()
{
struct invent product[3],*ptr;
printf(“INPUT \n\n”);

for(ptr=product;ptr<product+3;ptr++)
scanf(“%s%d%f”,ptrname,&ptrnumber,&ptrprice);

printf(“\n OUTPUT \n\n”);


ptr=product;
while(ptr<product+3)
{
printf(“%-20s%5d%10.2f\n”,ptrname, ptrnumber, ptrprice);
ptr++;
}
}

✧ Structures,Unions and Preprocessors

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 24


CPS[18CPS13]
MODULE-5

Arrays can be used to represent a group of data items that belong to the same type
such as int or float. But, arrays cannot be used if we want to represent a collection of
data items of different types using a single name.

C supports a constructed data type known as structures.

DEFINING A STRUCTURE
Structure are collection of different data type grouped together under a single
variable name for convenient handling.
'struct' is a keyword, struct type is a name which identifies the structure.
syntax :
struct<structure name or tag name >
{
datatype member 1;
datatype member 2;
};
In defining the structure:
✔ The template is terminated with semicolon.
✔ Entire definition is considered as statement ,each member is declared
independently for its name and type in sepearate statement inside the template.
✔ the tag name can be used to declare structure varaible of its type,later in the
program.
✔ Example:Consider a book database consisting of book name,author,number of
pages,and price.

Arrays Structures

Collection of related data el Can have elements of different type


ements of same type

Derived data type Programmer/User defined type

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 25


CPS[18CPS13]
MODULE-5

Behaves like built-in data ty Design and declare a data structure before the variables of
pe that type are declared and used

Structure declaration:
A structure can be declared using three different ways as shown below.
✔ Tagged Structures
✔ Structure without tag
✔ Type defined structures

● Tagged structure:

✔ In the structure definition, the keyword struct can be followed by an identifier.


This identifier is called tag name.
✔ The structure definition associated with a tag name is called tagged structure.

syntax Example

struct tag_name struct student


{ {
type member1; char name[10];
type member2; int usn_number;
..……. float average_marks;
};
};

The syntax for declare structure variables


Syntax:
struct tag_name V1, V2,….Vn;

Example: struct student cse,ise;

The complete structure definition along with structure declaration is shown below:
struct student

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 26


CPS[18CPS13]
MODULE-5
{
char name[10];
int usn_number; /* Structure definition */
float average_marks;
};
struct student cse, ise; /* structure declaration */
Once the variables are declared, the memory for the variables cse and ise are
allocated.
10 byted are allocated for the field name.
2 bytes for the field usn_number.
4 bytes for the field average_marks.
10+2+4=16 bytes

● Structure without tag


✔ In the structure definition, the keyword struct can be followed by an identifier.
This identifier is called tag name and it is optional.
✔ The structure definition without tag name is called structure without tag.

syntax Example
struct struct
{ {
type member1; char name[10];
type member2; int usn_number;
..……. float average_marks;
} cse,ise;
} v1,v2…..vn;

● Type - Defined Structure


The structure definition associated with the keyword typedef is called Type defined
structure.

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 27


CPS[18CPS13]
MODULE-5

syntax Example
type def struct Type def struct
{ {
type member1; char name[10];
type member2; int usn_number;
..……. float average_marks;

} TYPE_ID; } STUDENT;

The complete structure definition along with typedef definition and declaration
typedef struct
{
char name[10];
int usn_number;
float average_marks;
} STUDENT;
STUDENT cse,ise; /*Structure declaration */

Structure initialization:
The syntax is shown below :
struct tag_name variable = { v1, v2,…vn};
“struct tag_name” is derived data type.
v1,v2..vn are all initial values.
These values are called initializers.
The structure definition, declaration and initialization

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 28


CPS[18CPS13]
MODULE-5

OR
struct employee
{ struct employee
Char name[20]; {
Int salary; char name[10];
Int id; int salary;
} a={“Shiva”,10950,2001}; Int id;
};
Struct employee a={“Shiva”,10950,2001};

Initialization during structure declaration with more than one variable.

struct employee struct employee


{ {
char name[20]; char name[20];
int salary; int salary;
int id; int id;
}; }
struct employee a={“Rama”,2000,1000}; a={“Rama”,2000,1000},
struct employee b= {“Shiva”,10950,2001}; b= {“Shiva”,10950,2001};

During partial initialization

Example : struct employee a= {“Shivashankar”};

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 29


CPS[18CPS13]
MODULE-5
During initialization, the number of initializers should not exceed the number of
members.
Example : struct employee a= {“Rama”,10950,2001,10.2};
The compiler issues a syntax error
During initialization, there is no way to initialize members in the middle of a structure
without initializing the previous members.
Example: struct employee a= { 10950,2001}; is invalid
⮚ Accessing structures

The members of a structure are separate entities and should be processed be


individually.
A member of a structure can be accessed by specifying the variable name followed by
a period(also called dot) which in turn is followed by the member name .

Syntax: variable.member

Example:Consider the structure definition & initialization

struct employee
{
char name[10];
float salary;
int id;
};
struct employee a={“Shiva”,10950,2001};

The memory representation for the above structure

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 30


CPS[18CPS13]
MODULE-5

The various members can be accessed using the variable a as

a.name access the string “Shiva”


a.salary access the value 10950
a.id- access the value of 2001

We can read the name of an employee the salary and id as shown below:

gets(a.name);
scanf(“%f”,&a.salary);
Scanf(“%d”,&a.id);

The various members of a structure can be accessed and printed as shown below:

printf(“%s”,a.name);
printf(“%d”,a.salary);
printf(“%d”,a.id);

⮚ Define a structure type, struct personal that would contain person name,
date of joining and salary, write a program to read this information from the
keyboard and print the same on the screen.

struct personal
{
char name[20];
int day;
char month[10];

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 31


CPS[18CPS13]
MODULE-5
int year;
float salary;
};

main()
{
struct personal person;
printf(“ Input Values\n”);

scanf(“%s%d%s%d%f”,person.name,&person.day,person.month,&person.year,&pers
on.salary);

printf(“%s%d%s%d%f”,person.name,person.day,person.month,person.year,person.sal
ary);
}
⮚ Sizeof a structure(Concept of Slack Bytes)

The size of a structure is defined as the sum of sizes of each members of the
structures.

For example: Consider the structure declaration.

struct student
{
char name[10];
int roll_number;
double avg_marks;
}a;

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 32


CPS[18CPS13]
MODULE-5
The size of each member of the structure is
a.name array of 10 character 10 bytes
a.roll_number integer 4 bytes
a.avg_marks double 8 bytes

So, total size of the student = 22 bytes

If 2000 is the starting address of the variable a,then the starting address of each
member depends on sum of sizes of previous members.

Some times,the size of the structure will not be equal to sum of sizes of the individual
members .
This is because of slack bytes.

0 1 2 3
-char- Slack byte --------int---------
A character data takes one byte and an integer takes two bytes.
One byte between them is left unoccupied.
This unoccupied byte is known as the slack byte.
❖ Structure Operation:

The various operations can be performed on structures and structure members.

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 33


CPS[18CPS13]
MODULE-5
Copying comparing of two structure variables or members
Arithmetic operations on structure

✔ COPYING AND COMPARING TWO STRUCTURE VARIABLES OR


MEMBERS
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;

But the statements,

person1 == person2;
person2 != person1;

are not permitted.


C does not permit any logical operations on structure

The members of two structure variables of same type can be compared using
relational operators.
a.member1==b.member2
a.member1!=b.member2

⮚ ARITHMETIC OPERATIONS ON STRUCTURE


Member of the structure can be manipulated by using expressions and operators.
Example:
++a.salary;
a.salary++;

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 34


CPS[18CPS13]
MODULE-5
&a.salary;
&a;
❖ Pointer to structure:

A variable which contains address of a structure variable is called pointer to a


structure.

typedef struct
{
char name[10];
int usn_number;
float average_marks;
}STUDENT;

void main()
{
STUDENT a;
STUDENT *p;
P=&a;
}

Using this pointer various members of the structure can be accessed using two
methods:

1. Using de-referencing operator * and dot(.) operator.


2. Using selection operator()

Using de-referencing operator * and dot(.) operator:

If P is pointer to a structure, then the structure itself can be accessed using indirection
operator as shown below.

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 35


CPS[18CPS13]
MODULE-5
* p;

Once the structure is accessed, each members of the structure can be accessed using
dot operator.

(*p).name;
(*p).roll_number;
(*p).average_marks

Using selection operator()

Selection operator denoted by 


Using this operator, various members of the structure can be accessed as

Pname
Proll_number
Paverage_marks

⮚ Complex Structures:

Using structure we can deal with various complex problems.

✔ Nested structures
✔ Structure containing arrays
✔ Structure containing pointers
✔ Arrays of structure

⮚ Nested structures
A structure which includes another structure is called nested structure i.e, structure
can be used as a member of another structure.

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 36


CPS[18CPS13]
MODULE-5

struct subject typedef struct


{ {
int marks1; char name[10];
int marks2; int USN;
int marks3; struct subject marks;
}; }STUDENT;
STUDENT s;

s.marks.marks1; s.name;//Access name


s.marks.marks2; s.USN; //Access USN
s.marks.marks3;

❖ Structure containing arrays

✔ Arrays can be used within structure as members.

✔ A single or multi_dimensional array of int, float, char and double can be used
within the structures.

Example : structure definition which contains array as


members.

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 37


CPS[18CPS13]
MODULE-5

typedef struct s.name;//Access name


{ s.USN; //Access USN
char name[10]; s.marks[0];
int USN; s.marks[1];
int marks[3]; s.marks[2];
}STUDENT;
STUDENT s;

❖ Structure containing pointers

✔ Pointer can also be used as a member of the structure.


✔ Pointers are common when we use structure

Example : structure containing pointer as members.

typedef struct
{ d.day=“Thursday”;

char *day; d.Month = 11;


int month;
int year; d.Year = 1965;

}DATE;

DATE d;

❖ Array of Structures
As we have an array of integers, we can have an array of structures also.
Example:Suppose we want to store the information of 10 students consisting of
name,marks and year of passing.
typedef struct

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 38


CPS[18CPS13]
MODULE-5
{
char name[20];
int marks;
int year;
}STUDENT;

To store the information of more number of students,we can have the following
declaration.
STUDENT a[10];
LAB PROGRAM 13. Implement structures to read, write and compute average-
marks and the students scoring
above and below the average marks for a class of N students.
#include<stdio.h>
struct student
{
char name[20];
int rollno;
int m1, m2, m3;
int avg;
};
main( )
{
struct student s[100];
int n, i, sum=0, class_avg =0;
printf("Enter the number of students\n");
scanf("%d", &n);
// To read the details of 'n' students
printf("Enter the student details\n");
for(i=0; i<n; i++)
{
printf("Enter the name\n");
scanf("%s", s[i]. name);

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 39


CPS[18CPS13]
MODULE-5
printf("Enter the rollno\n");
scanf("%d", &s[i]. rollno);
printf("Enter the marks in three tests\n");
scanf("%d%d%d", &s[i].m1, &s[i].m2, &s[i].m3);
}
// To compute the average marks of each student
for(i=0; i<n; i++)
{
s[i].avg = ( s[i].m1 + s[i].m2 + s[i].m3) / 3;
}
// To compute the average marks of class
for(i=0; i<n; i++)
{
sum = sum + s[i].avg;
}
class_avg = sum / n;
printf("The average marks of class is %d\n", class_avg);
// To print the names of students scoring above average
printf("Above average students\n");
for(i=0; i<n; i++)
{
if( s[i].avg > = class_avg)
{
printf("%d\t", s[i].rollno);
printf("%s\n", s[i].name);
}
}
// To print the names of students scoring below average
printf("Below average students\n");
for(i=0; i<n; i++)
{

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 40


CPS[18CPS13]
MODULE-5
if( s[i].avg < class_avg)
{
printf("%d\t", s[i].rollno);
printf("%s\n", s[i].name);
}
}
return 0;
}

❖ STRUCTURES AND FUNCTIONS

Structure values can be passed as arguments to functions.


There are three methods by which the values of a structure can be transferred from
one function to another.

1. Each member of the structure can be passed as an actual argument of the


function call.
● The actual arguments are then treated independently like ordinary variables.
● This is the most elementary method and becomes unmanageable and inefficient
when the structure size is large.

2. The second method involves passing of a copy of the entire


structure to the called function.
● Any changes to structure members within the function are not reflected in the
original structure (in the calling function).
● It is therefore, necessary for the function to return the entire structure back to the
calling function.

3. The third approach employs a concept called pointers to pass


the structure as an argument.
● In this case, the address location of the structure is passed to the called function.

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 41


CPS[18CPS13]
MODULE-5
● The function can access indirectly the entire structure and work on it. This is
more efficient.
/* The general format of sending a copy of a structure to the called function is*/
function_name(structure_varaiable_name);
the called function takes the following form:
data_type function_name(struct_type st_name)
{
................
................
return(expression);
}
To illustrate the method of sending an entire structure as a parameter to a
function.

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 42


CPS[18CPS13]
MODULE-5

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 43


CPS[18CPS13]
MODULE-5

❖ Union and its definition:

✔ A union, is a collection of variables of different types, just like a structure.


✔ All these variables may contains data items of similar or dissimilar data type.
✔ Each variable in the union is called a member or a field.

Syntax :
union tag_name
{
type1 member 1;
type2 member 2;
……
};
Consider the following definition and declaration :
typedef union
{
int i;
double d; Union definition
char c;

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 44


CPS[18CPS13]
MODULE-5
}ITEM;

ITEM x; Union declaration


Another way of declaring the same variable X

union item
{
int i;
double d;
char c;
}x;

By using the dot operator(.) we can access various members of the union.

x.i;
x.d;
x.c;

X can also be declared as a pointer.

union item *x;

X->i OR (*x).i
x->d OR (*x).d
X->c OR (*x).c
Memory representation of Union:
union item
{
int m;
float x;
char c.;

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 45


CPS[18CPS13]
MODULE-5
}code;

/*Program to access various members of a union*/

#include<stdio.h>
void main()
{
typedef union
{
int marks;
char grade;
float percentage;
}STUDENT;

STUDENT x;

x.marks=100;

printf(“Marks=%d\n”,x.marks);

x.grade=‘A’;

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 46


CPS[18CPS13]
MODULE-5

printf(“Grade = %c\n”,x.grade);

x.percentage=99.5;

printf(“percentage = %f\n”,x.percentage);

}
❖ Preprocessors

It is a program that accepts a source program with preprocessing statements is the


input and produces another source program which not contain by preprocessing
statement.

The preprocessing statements also called preprocessor directive starts with symbol ‘#’
in C language.

The preprocessor directives are lines included in our programs that starts with
character #.

There are different types of preprocessor statements


✔ Macros
✔ File inclusion
✔ Conditional compilation

Symbolic name can be defined using #define directive whereas already defined
symbolic names can be undefined using #undef.
#define PI 3.146
#undef PI

⮚ Macros

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 47


CPS[18CPS13]
MODULE-5
A macro is the name given to group of statements.
A macro is defined using #define preprocessor directive.

Syntax: #define identifier string

Example : #define AREA (length*breadth)


#define NAME “KUMAR”
#define PRINT printf(“Enter the value\n”);

/* Program to find square of a number using macro */

#include<stdio.h>
#define SQUARE(x) (x*x)

void main()
{

int m,n;
n=5;
m=10;
printf(“ 5 square =%d\n”,SQUARE(n));
` printf(“ 10 square =%d\n”,SQUARE(m));
printf(“ 10+5 square =%d\n”,SQUARE(m+n));
}
O/P: 5 square=25
10 square=100
/* Program to find largest of two numbers using macro */

#include<stdio.h>
#define MAX(x,y)((x)>(y)?(x):(y))

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 48


CPS[18CPS13]
MODULE-5
void main()
{

int a,b,c;
printf(“ Enter two number\n”);
` scanf(“%d%d”,&a,&b);
c=MAX(a,b);
printf(“ Maximum =%d\n”,c);
}

Macro with arguments:

#define MAX(a,b) (((a)>(b))?(a):(b))

⮚ Nesting of macros:
we can also use one macro in the definition of another macro.
#define M 5
#define N M+1
#define square(x) ((x)*(x))
#define CUBE(x) (square(x)*x)
#define SIXTH(x) (CUBE(x)*CUBE(x))

⮚ File inclusion:

This is the process of inserting external files containg macros and function into the C
program.

File inclusion can be carried out by using #include preprocessor statement.

Syntax: #include filename

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 49


CPS[18CPS13]
MODULE-5
#include<stdio.h>
#include<string.h>
#include ”myfile.c”
#include “node.h”

Leave at least one space between #include and the filename.

#include ”myfile.c”: Searches first in the current directory


and then in the standard directories.

#include <myfile.c>:Searches only in the specified list of


directories(standard).

/*This Program illustrate file inclusion preprocessor statement*/

#include<stdio.h> File:factor.h
#include “factor.h”
Int fact(int n)
main() {
{ int f=1;
int number, f; If(n==0)
printf(“Enter the number\n”);
scanf(“%d”,&number); return(1);
f=fact(number);
else
printf(“Factorial of %d=%d\n”,number,f)
} return(n*fact(n-1))

⮚ Conditional Compilation:

The conditional compilation preprocessor statement is used to select alternate portions


of source program, depending on the value of one or more conditions.

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 50


CPS[18CPS13]
MODULE-5

The most frequently used conditional compilation statements are

#ifdef /* if defined */

#elif /* else if */

#endif

#else

#ifndef /* if not defined */

#undef /* undefined */

#if

#pragma

#error

Example:
main()
{
#ifdef VER1
code for version1
#else
code for version2
}
To run the first version version1.
Then #define the following statement before the main()

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 51


CPS[18CPS13]
MODULE-5
#define version 1

If Directive
main() #else
{ {
--- Statement 21;
-- Statement 21;
#if TEST<=4 .
{ .
Statement 11; Statement 2n;
Statement 12; }
.
Statementn; #endif
} }

Prof.Mithuna H.R,Dept of ISE,ACIT,BangalorePage 52

You might also like