Programming in C - Module V
Programming in C - Module V
Module Number: 05
AIM:
To familiarize the students with structures and pointers and how to implement in the
required locations
2
Pointers and Structures
Objectives:
3
Pointers and Structures
Outcome:
4
Pointers and Structures
Contents
1. Introduction
2. Pointers
3. Structures
5
Pointers and Structures
Introduction
6
Pointers and Structures
Overview of Pointers
Pointers in C are easy and fun to learn. Some C programming tasks are
performed more easily with pointers, and other tasks, such as dynamic
memory allocation, cannot be performed without using pointers. So it
becomes necessary to learn pointers to become a perfect C programmer.
Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory
location has its address defined which can be accessed using ampersand
(&) operator, which denotes an address in memory.
7
Pointers and Structures
What is Pointers?
Pointers
2. A NULL pointer.
program)
– Int *p 9
Pointers and Structures
Pointers
11
Pointers and Structures
Declaring pointer
Data-type *name;
14
Pointers and Structures
Declaring pointer
When you write int *, compiler assumes that any address that
it holds points to an integer type.
15
Pointers and Structures
Declaring pointer
Pointer Variable
We may access the value 547 by using either the name X or the
address 4000.
p = &quantity
Address-of operator(&)
Address-of operator(&)
Int *ptr; declaring variable ptr which holds the value at address of int
type
printf(“%d\n”, deref);
Output will be 1 20
Pointers and Structures
21
Pointers and Structures
22
Pointers and Structures
23
Pointers and Structures
24
Pointers and Structures
Pointer Conversions
25
Pointers and Structures
Generic Pointer
26
Pointers and Structures
Pointers in Detail
Pointers have many but easy concepts and they are very important to C
programming. The following important pointer concepts should be clear
to any C programmer:
Concept Description
Pointer arithmetic There are four arithmetic operators that can
be used in pointers: ++, --, +, -
Array of pointers You can define arrays to hold a number of
pointers.
Pointer to pointer C allows you to have pointer on a pointer
and so on.
Passing pointers to Passing an argument by reference or by
functions in C address enable the passed argument to be
changed in the calling function by the called
function. 27
Pointer Arithmetic
There are only two arithmetic operations that can be used on pointers
– Addition
– Subtraction
– int is of 2 bytes
Pointer Arithmetic
Each time p1 is incremented, it will point to next integer.
– for p1--;
Incrementing a Pointer
We prefer using a pointer in our program instead of an array because
the variable pointer can be incremented, unlike the array name which
cannot be incremented because it is a constant pointer. The following
#include <stdio.h>
program increments the variable pointer to access each succeeding
const int MAX = 3;
int main ()
{
element of the array: int var[] = {10, 100, 200}; Output
int i, *ptr;
/* let us have array address in pointer */
Address of var[0] = bf882b30
ptr = var;
Value of var[0] = 10
for ( i = 0; i < MAX; i++)
Address of var[1] = bf882b34
{
Value of var[1] = 100
printf("Address of var[%d] = %x\n", i, ptr
Address of var[2] = bf882b38
);
Value of var[2] = 200
printf("Value of var[%d] = %d\n", i,
*ptr );
/* move to the next location */
ptr++; 30
}
return 0;
}
Pointers and Structures
Decrementing a Pointer
The same considerations apply to decrementing a pointer, which
decreases#include
its value by the number of bytes of its data type as
<stdio.h>
const int MAX = 3;
shown below − () {
int main
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in
pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--) {
printf("Address of var[%d] = %x\ Output
n", i-1, ptr );
Address of var[2] = bfedbcd8
printf("Value of var[%d] = %d\n", i-
Value of var[2] = 200
1, *ptr );
Address of var[1] = bfedbcd4
/* move to the previous location */
Value of var[1] =31100
ptr--;
Address of var[0] = bfedbcd0
}
Value of var[0] = 10
return 0;
Pointers and Structures
#include <stdio.h>
const int MAX = 3;
int main () {
Pointer Comparisons int var[] = {10, 100, 200};
int i, *ptr;
Pointers may be compared by using /* let us have address of the first element in
pointer */
relational operators, such as ==, <, and ptr = var;
i = 0;
>. If p1 and p2 point to variables that
while ( ptr <= &var[MAX - 1] ) {
are related to each other, such as
printf("Address of var[%d] = %x\n", i, ptr );
elements of the same array, then p1 and printf("Value of var[%d] = %d\n", i, *ptr );
Dynamic Memory
Allocation
33
Pointers and Structures
As you know, you have to declare the size of an array before you use it. Hence,
the array you declared may be insufficient or more than required to hold data.
To solve this issue, you can allocate memory dynamically.
35
Pointers and Structures
C malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of specified size and return a pointer of
type void which can be casted into pointer of any form.
Syntax of malloc()
ptr = (cast-type*)
malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory
with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr = (int*) malloc(100 *
sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 36bytes respectively
and the pointer points to the address of first byte of memory.
Pointers and Structures
C calloc()
The name calloc stands for "contiguous allocation".
The only difference between malloc() and calloc() is that, malloc() allocates single
block of memory whereas calloc() allocates multiple blocks of memory each of same
This statement allocates contiguous space in memory for an array of 2537 elements each of
size of float, i.e, 4 bytes.
Pointers and Structures
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't
get freed on its own. You must explicitly use free() to release the space.
Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
38
Pointers and Structures
C realloc()
If the previously allocated memory is insufficient or more than required, you
Syntax of realloc()
ptr = realloc(ptr,
newsize);
41
Pointers and Structures
}
Pointers and Structures
Array of pointers
Before we understand the concept of arrays of pointers, let us consider
the following example, which uses an array of 3 integers −
#include <stdio.h>
int main () {
There may be a situation when we want to maintain int var[] = {10, 100, 200};
int i, *ptr[MAX];
an array, which can store pointers to an int or char
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i]; /* assign the address of
or any other data type available. Following is the integer. */
}
declaration of an array of pointers to an integer −
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
int *ptr[MAX]; }
return 0;
It declares ptr as an array of MAX integer pointers. }
Pointer 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 below.
Pointer Pointer Variable
#include <stdio.h>
#include <time.h>
Passing pointers to functions in
void getSeconds(unsigned long *par);
C
int main () {
C programming allows passing a unsigned long sec;
getSeconds( &sec );
pointer to a function. To do so, simply
/* print the actual value */
declare the function parameter as a printf("Number of seconds: %ld\n", sec );
Output
the function which reflects back in the 48
Arithmetic Rules
52
Pointers and Structures
Structures
53
Pointers and Structures
What is structures?
54
Pointers and Structures
Structures
Arrays allow to define type of variables that can hold several data
items of the same kind. Similarly, structure is another user-defined
data type available in C that allows to combine data items of
different kinds. Structures are used to represent a record. Suppose
you want to keep track of your books in a library. You might want to
track the following attributes about each book:
Title
Author
Subject
Book ID
55
Pointers and Structures
Defining a structure
To define a structure, you must use the struct statement. The struct
statement defines a new data type, with more than one member. The
format of the struct statement is as follows −
Syntax:
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
56
Pointers and Structures
Defining a structure
Defining a structure
Structure initialization
Syntax:
60
Pointers and Structures
Partial initialization
We can initialize the first few members and leave the remaining
blank.
struct student
{
char name[20];
int roll;
char remarks;
float marks;
};
void main()
{
struct student s1={“name", 4};
clrscr();
printf("Name=%s", s1.name);
printf("n Roll=%d", s1.roll);
printf("n Remarks=%c", s1.remarks);
printf("n Marks=%f", s1.marks); getch(); 62
}
Pointers and Structures
int main()
{
struct person person1, person2,
person3[20];
return 0; 63
}
Pointers and Structures
64
Pointers and Structures
person2.salary
Suppose, we want to access salary for variable person2. Then, it
can be accessed as:
65
Pointers and Structures
int main()
{ printf("1st distance\n");
Example of structure // Input of feet for structure variable dist1
printf("Enter feet: ");
scanf("%d", &dist1.feet);
Write a C program to add two distances // Input of inch for structure variable dist1
printf("Enter inch: ");
entered by user. Measurement of scanf("%f", &dist1.inch);
printf("2nd distance\n");
distance should be in inch and feet. // Input of feet for structure variable dist2
printf("Enter feet: ");
(Note: 12 inches = 1 foot) scanf("%d", &dist2.feet);
// Input of feet for structure variable dist2
printf("Enter inch: ");
Output scanf("%f", &dist2.inch);
sum.feet = dist1.feet + dist2.feet;
1st distance sum.inch = dist1.inch + dist2.inch;
Enter feet: 12 if (sum.inch > 12)
{
Enter inch: 7.9 //If inch is greater than 12, changing it to feet.
2nd distance ++sum.feet;
Enter feet: 2 sum.inch = sum.inch - 12; }
Enter inch: 9.8 // printing sum of distance dist1 and dist2
printf("Sum of distances = 66 %d\'-%.1f\"", sum.feet,
Sum of distances = 15'-5.7" sum.inch);
return 0; }
Pointers and Structures
#include <stdio.h>
#include <string.h>
struct Books {
Accessing Structure Members char title[50];
char author[50];
char subject[100];
int book_id;
};
To access any member of a structure, we use the int main( ) {
struct Books Book1; /* Declare Book1 of type
/* book 2 specification */
member that we wish to access. You would use strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
the keyword struct to define variables of /* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
structure type. The following example shows how printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
return 0;}
Pointers and Structures
You can pass a structure as a function argument in the same way as you
pass any other variable or pointer.
#include <stdio.h> /* book 1 specification */
#include <string.h> /* Print Book2 info */
strcpy( Book1.title, "C Programming");
struct Books { printBook( Book2 );
strcpy( Book1.author, "Nuha Ali");
char title[50]; return 0;
strcpy( Book1.subject, "C Programming
char author[50]; Tutorial"); void printBook( struct Books book ) {
struct student
{
char name[20]; Here, structure has
int roll; been declared global
}; i.e. outside of main()
void main()
{
function. Now, any
struct student student1={“ABC", 4, }; function can access it
struct student student2; and create a
clrscr(); structure variable.
student2=student1;
printf("nStudent2.name=%s",
student2.name);
printf("nStudent2.roll=%d", student2.roll);
If(strcmp(student1.name,student2.name)
==0 &&
(student1.roll==student2.roll))
{
printf("nn student1 and student2 are 72
same.");
}
Pointers and Structures
Array of Structure
74
Pointers and Structures
Array of Structure
75
Pointers and Structures
76
Pointers and Structures
Array of Structure
Let us consider we have a structure as:
struct student
{
char name[20];
int roll;
char remarks;
float marks;
};
If we want to keep record of 100 students, we have to make 100 structure
variables like st1, st2, …,st100.
In this situation we can use array of structure to store the records77 of 100
students which is easier and efficient to handle (because loops can be used).
Pointers and Structures
Array of structure
• Two ways to declare an array of structure:
Write a program
That takes roll_no, fname lname of 5 students and prints the same
records in ascending order on the basis of roll_no
Reading values Sorting values
}
Pointers and Structures
Reading Values
for(i=0;i<n;i++)
{
printf("n Enter information about student%d",i+1);
printf("n Name:t"); scanf(" %s", s[i].name);
printf("n Class:t"); scanf("%d", &s[i]._class);
printf("n Section:"); scanf(" %c", &s[i].section);
printf("n Input marks of 6 subjects:t");
for(j=0;j<6;j++)
{
scanf("%f", &temp);
s[i].marks[j]=temp;
81
}
}
Pointers and Structures
another structure.
Pointers and Structures
struct personal_record
char name[20];
int day_of_birth;
int month_of_birth;
int year_of_birth;
float salary; 83
}person;
Pointers and Structures
85
Pointers and Structures
printf("Enter name:t");
scanf("%s", person.name);
printf("nEnter day of birthday:t");
scanf("%d", &person.birthday.day_of_birth);
printf("nEnter month of birthday:t");
scanf("%d", &person.birthday.month_of_birth);
printf("nEnter year of birthday:t");
scanf("%d", &person.birthday.year_of_birth);
printf("nEnter salary:t"); scanf("%f", &person.salary);
86
Pointers and Structures
struct date
{
int day;
int month;
int year;
};
struct name
{
char first_name[10];
char middle_name[10];
char last_name[10];
};
struct personal_record
{
float salary;
struct date
birthday,deathday; 87
Pointers to Structure
You can define pointers to structures in the same way as you define
pointer to any other variable −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above
defined pointer variable. To find the address of a structure variable,
place the '&'; operator before the structure's name as follows −
struct_pointer = &Book1;
int main( ) { strcpy( Book2.title, "Telecom Billing"); printf( "Book subject : %s\n", book-
>subject);
strcpy( Book2.author, "Zara Ali");
printf( "Book
89 book_id : %d\n", book-
strcpy( Book2.subject, "Telecom Billing
>book_id);
Tutorial");
}
Book2.book_id = 6495700;
Pointers and Structures
91
Pointers and Structures
92
Pointers and Structures
display(emp.name,emp.id,emp.salary);
printf("nNamettIDttSalaryn);
printf("%st%dt%.2f",e,id,sal);
93
Pointers and Structures
function_name(structure_variable_name);
… … … … …;
94
}
Pointers and Structures
display(emp);
printf("nNametIDtSalaryn");
printf("%st%dt%.2f",e.name,e.id,e.salar);
95
Pointers and Structures
Note: Any changes made to the members in the called function are
directly reflected in the calling function.
96
Pointers and Structures
display(&emp);
printf("nNametIDtSalaryn");
printf("%st%dt%.2f",e->name,e->id,e->salary);
97
Pointers and Structures
That is, the name of the array of structure is passed by the calling
function which is the base address of the array of structure.
98
Pointers and Structures
Bit Fields
Bit Fields allow the packing of data in a structure. This is especially useful
when memory or data storage is at a premium. Typical examples include −
Packing several objects into a machine word. e.g. 1 bit flags can be
compacted.
Reading external file formats -- non-standard file formats could be read in,
e.g., 9-bit integers.
C allows us to do this in a structure definition by putting :bit length after the
variable. For example −
struct packed_struct Here, the packed_struct contains 6 members:
{ unsigned int f1:1; Four 1 bit flags f1..f3, a 4-bit type and a 9-bit
unsigned int f2:1; my_int. C automatically packs the above bit fields
unsigned int f3:1; as compactly as possible, provided that the
unsigned int f4:1; maximum length of the field is less than or equal
unsigned int type:4; to the integer word length of the computer. If this
unsigned int my_int:9; is not the case, then some compilers may allow
} pack; memory overlap for the fields while others 100 would
101
Pointers and Structures
#include <stdio.h>
A. 10
void foo(int*);
B. Some garbage value int main()
C. Compile time error {
D. Segmentation fault int i = 10, *p = &i;
foo(p++);
}
void foo(int *p)
{
Answer: 10 printf("%d\n", *p);
}
102
Pointers and Structures
103
Pointers and Structures
4. Which of the following are correct syntaxes to send an array as a parameter to function:
A. func(&array);
B. func(#array);
C. func(*array);
D. func(array[size]);
Answer: func(&array);
104
Pointers and Structures
A. string
B. structures
C. char
D. all of the mentioned
Answer: structures
105
Pointers and Structures
A. –
B. <-
C. .
D. Both <- and .
Answer: .
106
Pointers and Structures
A. struct temp{}s;
main(){}
B. struct temp{};
struct temp s;
main(){}
C. struct temp s;
struct temp{};
main(){}
D. None of the mentioned
108
Pointers and Structures
#include <stdio.h>
9. What is the output of this C code?. void main()
{
A. Nothing struct student
{
B. Compile time error int no;
C. Junk char name[20];
};
D. 8 struct student s;
s.no = 8;
printf("%d", s.no);
Answer: 8 }
109
Pointers and Structures
110
Pointers and Structures
Document Links
https://www.tutorialspoint.com/cprogr
amming/c_structures.htm This link describes about the structures and including the sample codes based on
Structures
https://www.geeksforgeeks.org/ the topics to execute and explain
structures-c/
111
Pointers and Structures
Video Links
https://www.youtube.com/watch?
Arrays This video explains the what is arrays
v=0EgpeYB115s
https://www.youtube.com/watch?v=-
Functions This video explains the function with sample code
VFjwqenkVM
https://www.youtube.com/watch?
Return Values This video explains implementation methods of it
v=TxWKGhF9KdM
112
Pointers and Structures
Assignment
• Define a structure of employee having data members name, address, age and salary. Take
data for n employee in an array dynamically and find the average salary.
• Explain how to create pointers to arrays.
• What is dangling pointer.
• With the function declaration explain malloc() function.
• With the function declaration explain calloc() function.
• Define a structure of student having data members name, address, marks in C language,
and marks in information system. Take data for n students in an array dynamically and
find the total marks obtained.
113
Pointers and Structures
EBook's Links
http://www-personal.acfr.usyd.edu.au/tbailey/ctext/ctext.pdf
Page Number 49- Page Number 57
Pointers https://www.tutorialspoint.com/cprogramming/cprogramming_tutorial.pdf
Page Number 101 - Page Number 114
114
Pointers and Structures
Thank you
115