0% found this document useful (0 votes)
4 views

Programming in C - Module V

Uuu

Uploaded by

jraj46183
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Programming in C - Module V

Uuu

Uploaded by

jraj46183
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 115

Programming in C

Module Number: 05

Module Name: Pointers and Structures


Pointers and Structures

AIM:

To familiarize the students with structures and pointers and how to implement in the
required locations

2
Pointers and Structures

Objectives:

The Objectives of this module are:

• Explain about the pointers and their importance


• Explain about pointers in detail
• Learn what is dynamic memory allocation with examples
• Understand what are structures and initialization methods

3
Pointers and Structures

Outcome:

At the end of this module, you are expected to:

• Identify the contents and address of a memory location.


• Pointer and its use
• Difference between a pointer variable and a normal variable.
• Passing structures by reference.

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?

 A variable that holds a memory address.

 This address is the location of another object in the memory.

 Pointer as an address indicates where to find an object.

 Not all pointers actually contain an address

 example NULL pointer.

 Value of NULL pointer is 0.


8
Pointers and Structures

 Pointers

 Pointer can have three kinds of content in it

1. The address of an object, which can be dereferenced.

2. A NULL pointer.

3. Invalid content, which does not point to an object.

 (If p does not hold a valid value, it can crash the

program)

 If p is a pointer to integer, then

– Int *p 9
Pointers and Structures

 Pointers

 It is possible in some environments to have multiple pointer values


with different representations that point to same location in memory.
Memory
Different pointers
holding same
P address
P P P
1 2 3 4

 But make sure if the memory is deleted using delete or if original


variable goes out of scope. 10
Pointers and Structures

 Example for Pointers

11
Pointers and Structures

 Understanding Pointers Memory Cell Address


0
 1
The computer’s memory is a sequential collection of storage
cells 2
3
 Each cell. Commonly known as a byte, has a number called
.
address associated with it
.
 The address are numbers consecutively, starting from zero .
 The last address depends on the memory size .
 A computer system having 64K memory will have its last ..
address as 65,535 .
65,535
12
Pointers and Structures

 Key points to remember about pointers in C:


 Normal variable stores the value whereas pointer variable stores the address of the
variable.
 The content of the C pointer always be a whole number i.e. address.
 Always C pointer is initialized to null, i.e. int *p = null.
 The value of null pointer is 0.
 & symbol is used to get the address of the variable.
 * symbol is used to get the value of the variable that the pointer is pointing to.
 If a pointer in C is assigned to NULL, it means it is pointing to nothing.
 Two pointers can be subtracted to know how many elements are available between
these two pointers.
 But, Pointer addition, multiplication, division are not allowed. 13

 The size of any pointer is 2 byte (for 16 bit compiler).


Pointers and Structures

 Declaring pointer

Data-type *name;

 * is a unary operator, also called as indirection operator.

 Data-type is the type of object which the pointer is pointing.

 Any type of pointer can point to anywhere in the memory.

 * is used to declare a pointer and also to dereference a pointer.

14
Pointers and Structures

 Declaring pointer

 When you write int *, compiler assumes that any address that
it holds points to an integer type.

 m= &count; it means memory address of count variable is


stored into m. & is unary operator that returns the memory
address.

i.e. & (orally called as ampersand) is returning the address.

15
Pointers and Structures

 Declaring pointer

 so it means m receives the address of count. 2000 Count=100


 Suppose, count uses memory Address 2000 to store
its value 100. so, m=&count means m has 2000
address.

 q= *m it returns the value at address m. value at


address 2000 is 100. so, q will return value 100.

i.e. q receives the value at address m.m 16


Pointers and Structures

 Pointer Variable

 We may access the value 547 by using either the name X or the
address 4000.

 Since memory addresses are simply numbers, they can be assigned to


some variables, that can be stored in memory, like any other variable.

 Such variables that hold memory addresses are called pointer


variables.

 A pointer variable is, nothing but a variable that contains an address,


which is a location of another variable in memory. 17
Pointers and Structures

 Accessing the address of a variable

 The actual location of a variable in the memory is system dependent.

 We can determine the address of a variable with the help of the


operator & available in C.

 The operator & immediately preceding a variable returns the address


of the variable associated with it.

p = &quantity

 Would assign the address 5000 to the variable p


18
Pointers and Structures

 Address-of operator(&)

 It is used to reference the memory address of a variable.

 When we declare a variable, 3 things happen

– Computer memory is set aside for variable

– Variable name is linked to that location in memory

– Value of variable is placed into the memory that was set


aside.
19
Pointers and Structures

 Address-of operator(&)

 Int *ptr; declaring variable ptr which holds the value at address of int
type

 int val =1; assigning int the literal value of 1

 ptr=&val; dereference and get value at address stored in ptr

 int deref =*ptr

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

 One type of pointer can be converted to another type of pointer.


int main() {
double x=100.1, y;
int *p;
p= (int *) &x; //explicit type conversion
y= *p;
}

25
Pointers and Structures

 Generic Pointer

 void * pointer is called as generic pointer.

 Can’t convert void *pointer to another pointer and vice-versa.

 void *pointer can be assigned to any other type of pointer.

 void * is used to specify a pointer whose base type is unknown.

 It is capable of receiving any type of pointer argument without reporting


any type of mismatch.

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

Return pointer from C allows a function to return a pointer to the


functions in C local variable, static variable, and
Pointers and Structures

 Pointer Arithmetic
 There are only two arithmetic operations that can be used on pointers

– Addition

– Subtraction

 To understand this concept, lets p1 be an integer pointer with value


2000 address.

– int is of 2 bytes

– After expression p1++;

– P1 contains address 2002 not 2001. 28


Pointers and Structures

 Pointer Arithmetic
 Each time p1 is incremented, it will point to next integer.

 The same is true for decrement.

– for p1--;

– Causes value of p1 to be 1998.

 Each time a pointer is incremented, it points to the memory


location of the next element of its base type.

 If decremented, then it points to previous element location.


29
 P1=p1+12; makes p1 points to 12th element of p1 type.
Pointers and Structures

 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 );

p2 can be meaningfully compared. /* point to the previous location */


ptr++;
 The following program modifies the i++;

previous example − one by }


return 0;
incrementing the variable pointer so }

long as the address to which it points is Output


either less than or equal to the address Address of var[0] = bfdbcb20
Value of var[0] = 10
of the last element of the array, which is Address of var[1] = bfdbcb24
Value of var[1] = 10032
&var[MAX - 1] − Address of var[2] = bfdbcb28
Value of var[2] = 200
Pointers and Structures

Dynamic Memory
Allocation

33
Pointers and Structures

 Dynamic Memory Allocation

 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.

 Dynamic memory management refers to manual memory management. This


allows you to obtain more memory when required and release it when not
necessary.

 Although C inherently does not have any technique to allocate memory


dynamically, there are 4 library functions defined under <stdlib.h>
34 for dynamic
memory allocation.
Pointers and Structures

 Functions and uses of function

Function Use of Function

Allocates requested size of bytes and returns a pointer first


malloc()
byte of allocated space
Allocates space for an array elements, initializes to zero and
calloc()
then returns a pointer to memory
free() deallocate the previously allocated space
realloc() Change the size of previously allocated space

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

size and sets all bytes to zero.


ptr = (cast-type*)calloc(n,
 Syntax of calloc()element-size);
This statement will allocate contiguous space in memory for an array of n elements. For
example: ptr = (float*) calloc(25,
sizeof(float));

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

 Example #1: Using C malloc() and free()


 Write a C program to find sum of n elements entered by user. To
perform this program, allocate memory dynamically using malloc()
function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated
using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
39
free(ptr);
return 0;
}
Pointers and Structures

 Example #2: Using C calloc() and free()


 Write a C program to find sum of n elements entered by user. To
perform this program, allocate memory dynamically using calloc()
function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) calloc(num, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr); 40
return 0;
}
Pointers and Structures

 C realloc()
 If the previously allocated memory is insufficient or more than required, you

can change the previously allocated memory size using realloc().

 Syntax of realloc()
ptr = realloc(ptr,
newsize);

Here, ptr is reallocated with size of newsize.

41
Pointers and Structures

 Example #3: Using realloc()


#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Address of previously allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%u\t",ptr + i);

printf("\nEnter new size of array: ");


scanf("%d", &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; ++i)
printf("%u\t", ptr + i);
return 0; 42

}
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>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};


Output
int i;

for (i = 0; i < MAX; i++) {


printf("Value of var[%d] = %d\n", i, var[i] ); Value of var[0] = 10
} Value of var[1] = 100
43
return 0; Value of var[2] = 200
}
Pointers and Structures
#include <stdio.h>

const int MAX = 3;


 Array of pointers
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. }

Thus, each element in ptr, holds a pointer to an int Output


value. The following example uses three integers,
which are stored in an array of pointers, as follows Value of var[0] = 10
Value of var[1] = 100
− 44
Value of var[2] = 200
Pointers and Structures

 Example of Array of pointers


 You can also use an array of pointers to character to store a list of
#include <stdio.h>
strings as int
const follows
MAX =− 4;
int main () {
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali" Value of names[0] = Zara
}; Output
int i = 0; Ali
for ( i = 0; i < MAX; i++) { Value of names[1] = Hina
printf("Value of names[%d] = %s\n", i,
names[i] ); Ali
} Value of names[2]
45 = Nuha
return 0;
} Ali
Pointers and Structures

 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

Address Address Value

 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.
46
For example,
the following declaration declares a pointer to a pointer of type int −
int **var;
Pointers and Structures

 Example of pointer to pointer


 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 −can also use an array of
pointers to character
#include <stdio.h> to store a list of strings as follows −
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of
operator & */ Output
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var ); Value of var = 3000
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", Value available at *ptr = 3000
47
**pptr);
return 0; Value available at **pptr = 3000
}
Pointers and Structures

#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 );

pointer type. return 0;


}
 Following is a simple example where void getSeconds(unsigned long *par) {
/* get the current number of seconds */
we pass an unsigned long pointer to a *par = time( NULL );
return;
function and change the value inside }

Output
the function which reflects back in the 48

Number of seconds :1294450468


calling function −
Pointers and Structures

 Example for passing pointers to functions in C


 The function, which can accept a pointer, can also accept an array as
#include <stdio.h>
shown in the following example −
/* function declaration */
double getAverage(int *arr, int size);
int main () {
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf("Average value is: %f\n", avg );
return 0;
}
double getAverage(int *arr, int size) { Output
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i) { Average value is: 214.40000
sum += arr[i];
}
avg = (double)sum / size; 49
return avg;
}
Pointers and Structures

 Return pointer from functions in C


 We have seen in the last chapter how C programming allows to return
an array from a function. Similarly, C also allows to return a pointer
from a function. To do so, you would have to declare a function
returning a pointer as in
int * myFunction() { the following example −
.
.
.
}

 Second point to remember is that, it is not a good idea to return the


address of a local variable outside the function, so you would have to
define the local variable as static variable.
 Now, consider the following function which will generate 10 random
50
numbers and return them using an array name which represents a
pointer, i.e., address of first array element.
Pointers and Structures
#include <stdio.h>
#include <time.h>
/* function to generate and return random
 Example for return pointer from functions in C numbers. */
int * getRandom( ) {
1523198053 static int r[10];
1187214107 int i;
1108300978 /* set the seed */
Output : 430494959
srand( (unsigned)time( NULL ) );
1421301276
for ( i = 0; i < 10; ++i) {
930971084
r[i] = rand();
123250484 printf("%d\n", r[i] );
106932140 }
1604461820 return r;
149169022 }
*(p + [0]) : 1523198053 /* main function to call above defined function
*(p + [1]) : 1187214107
*/
int main () {
*(p + [2]) : 1108300978
/* a pointer to an int */
*(p + [3]) : 430494959
int *p;
*(p + [4]) : 1421301276 int i;
*(p + [5]) : 930971084 p = getRandom();
*(p + [6]) : 123250484 for ( i = 0; i < 10; i++ ) {
*(p + [7]) : 106932140 printf("*(p + 51 [%d]) : %d\n", i, *(p + i) );
*(p + [8]) : 1604461820 }
*(p + [9]) : 149169022
return 0;
}
Pointers and Structures

 Arithmetic Rules

 You cannot multiply or divide pointers.

 You cannot add or subtract two pointers.

 You cannot apply bitwise operators to them.

 You cannot add or subtract type float or

 Double to or from pointers.

52
Pointers and Structures

Structures

53
Pointers and Structures

 What is structures?

 A structure is a collection of variables of different data types


under a single name.

 The variables are called members of the structure.

 The structure is also called a user-defined data type.

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

 Each variable of structure has its own copy of member


variables.
 The member variables are accessed using the dot (.) operator
or member operator.
 For example: st1.name is member variable name of st1
structure variable while st3.gender is member variable
gender of st3 structure variable.
57
Pointers and Structures

 Defining a structure

The structure definition The use of structure_name is


and variable declaration optional.
can be combined as:
struct student struct
{ {
char name[20]; char name[20];
int roll_no; int roll_no;
float marks; float marks; char
gender;
char gender;
long int phone_no;
long int
}st1, st2, st3;
phone_no;
}st1, st2, st3; 58
Pointers and Structures

 Structure initialization
 Syntax:

struct structure_name structure_variable={value1, value2, … ,


valueN};

 There is a one-to-one correspondence between the members and


their initializing values.

 Note: C does not allow the initialization of individual structure


members within the structure definition template.
59
Pointers and Structures

60
Pointers and Structures

 Partial initialization
 We can initialize the first few members and leave the remaining
blank.

 However, the uninitialized members should be only at the end of


the list.

 The uninitialized members are assigned default values as follows:

 – Zero for integer and floating point numbers.

 – ‘0’ for characters and strings.


61
Pointers and Structures

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

 Structure variable declaration


When a structure is defined, it creates a user-defined type but, no
storage or memory is allocated.
For the above structure of a person, variable can be declared as:
struct person
{
char name[50];
int citNo;
float salary;
};

int main()
{
struct person person1, person2,
person3[20];
return 0; 63

}
Pointers and Structures

 Structure variable declaration

Another way of creating a structure variable is:


struct person
{
char name[50];
int citNo;
float salary;
} person1, person2, person3[20];

In both cases, two variables person1, person2 and an


array person3 having 20 elements of type struct person are created.

64
Pointers and Structures

 Accessing members of a structure

There are two types of operators used for accessing members of


a structure.
Member operator(.)
Structure pointer operator(->) (is discussed in structure and
pointers tutorial)
structure_variable_name.member_name
Any member of a structure can be accessed as:

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

member access operator (.). The member Book */


struct Books Book2; /* Declare Book2 of type
Book */

access operator is coded as a period between the /* book 1 specification */


strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
structure variable name and the structure Book1.book_id = 6495407;

/* 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);

to use a structure in a program − /* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
67
printf( "Book 2 book_id : %d\n", Book2.book_id);

return 0;}
Pointers and Structures

 Accessing Structure Members

When the above code is compiled and executed, it produces the


following result −
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
68
Pointers and Structures

 Structures as Function Arguments

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 ) {

char subject[100]; Book1.book_id = 6495407; printf( "Book title : %s\n", book.title);

int book_id; /* book 2 specification */ printf( "Book author : %s\n",


book.author);
}; strcpy( Book2.title, "Telecom Billing");
printf( "Book subject : %s\n",
/* function declaration */ strcpy( Book2.author, "Zara Ali");
book.subject);
void printBook( struct Books book ); strcpy( Book2.subject, "Telecom Billing
printf( "Book book_id : %d\n",
Tutorial");
int main( ) { book.book_id);
Book2.book_id = 6495700;
struct Books Book1; /* Declare Book1 of }
type Book */ /* print Book1 info */
69

struct Books Book2; /* Declare Book2 of printBook( Book1 );


type Book */
Pointers and Structures

 Structures as Function Arguments

When the above code is compiled and executed, it produces the


following result −
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700
70
Pointers and Structures

 Copying and comparing structure Variable


 Two variables of the same structure type can be copied in the same
way as ordinary variables.
 If student1 and student2 belong to the same structure, then the
following statements are valid: student1=student2;
student2=student1;
 However, the statements such as:
student1==student2
student1!=student2
are not permitted.
 If we need to compare the structure variables, we may do 71
so by
comparing members individually.
Pointers and Structures

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

 How structure elements are stored?


 The elements of a structure are always stored in contiguous memory
locations.
 A structure variable reserves number of bytes equal to sum of bytes
needed to each of its members.
 Computer stores structures using the concept of “word boundary”.
In a computer with two bytes word boundary, the structure variables
are stored left aligned and consecutively one after the other (with at
most one byte unoccupied in between them called slack byte).
 When we declare structure variables, each one of them may contain
slack bytes and the values stored in such slack bytes are undefined.
 Due to this, even if the members of two variables are equal, their
structures do not necessarily compare.
73
 That’s why C does not permit comparison of structures.
Pointers and Structures

 Array of Structure

74
Pointers and Structures

 Array of Structure

75
Pointers and Structures

 Array inside 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:

struct student struct student


{ {
char name[20]; char name[20];
int roll; int roll;
char remarks; char remarks;
float marks; float marks;
}st[100]; };
struct student st[100];
20
78
Pointers and Structures

 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

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


{ {
printf("n Enter roll number:"); for(j=i+1; j<5; j++)
scanf("%d", &s[i].roll_no); {
if(s[i].roll_no<s[j].roll_no)
printf("n Enter first name:"); {
scanf("%s", &s[i].f_name); temp = s[i].roll_no;
s[i].roll_no=s[j].roll_no;
printf("n Enter Last name:"); s[j].roll_no=temp;
scanf("%s", &s[i].l_name); }
} }
79

}
Pointers and Structures

 Array within Structure


 We can use single or multi dimensional arrays of type int or float.
 E.g.
struct student
{
char name[20];
int roll;
float marks[6];
};
struct student s[100];
 Here, the member marks contains six elements, marks[0], marks[1], …, marks[5]
indicating marks obtained in six different subjects.
 These elements can be accessed using appropriate subscripts.
80
 For example, s[25].marks[3] refers to the marks obtained in the fourth subject by the
26th student.
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

 What is Structure within another structure or (Nested


Structure)

 Nested Structure in C is nothing but structure within structure . One


Structure can be declared inside other structure as we declare
structure members inside a structure. The structure variables to
access the data.

 Nested structures are allowed in C programming Language

 We can write one Structure inside another structure as member of


82

another structure.
Pointers and Structures

 Structure within another structure or (Nested Structure)


 Let us consider a structure personal_record to store the information of a person
as:

 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

 Structure within another structure or (Nested Structure)


 In the structure above, we can group all the items related to birthday together
and declare them under a substructure as:
struct Date
{
int day_of_birth;
int month_of_birth;
int year_of_birth;
};
struct personal_record
{
char name[20];
struct Date birthday;
84
float salary;
}person;
Pointers and Structures

 Structure within another structure or (Nested Structure)

 Here, the structure personal_record contains a member named birthday which


itself is a structure with 3 members. This is called structure within structure.
 The members contained within the inner structure can be accessed as:
person.birthday.day_of_birth
person.birthday.month_of_birth
person.birthday. year_of_birth
 The other members within the structure personal_record are accessed as usual:
person.name
person.salary

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

struct name full_name;


Pointers and Structures

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

To access the members of a structure using a pointer to that


structure, you must use
struct_pointer->title; the → operator as follows − 88
Pointers and Structures

 Example for Pointers to Structure

Let us re-write the above example using structure pointer.


struct Books Book1; /* Declare Book1 of /* print Book1 info by passing address of
#include <stdio.h>
type Book */ Book1 */
#include <string.h>
struct Books Book2; /* Declare Book2 of printBook( &Book1 );
struct Books { type Book */ /* print Book2 info by passing address of
char title[50]; /* book 1 specification */ Book2 */
char author[50]; strcpy( Book1.title, "C Programming"); printBook( &Book2 );
char subject[100]; strcpy( Book1.author, "Nuha Ali"); return 0;
int book_id; strcpy( Book1.subject, "C Programming void printBook( struct Books *book ) {
}; Tutorial"); printf( "Book title : %s\n", book->title);
/* function declaration */ Book1.book_id = 6495407; printf( "Book author : %s\n", book-
void printBook( struct Books *book ); /* book 2 specification */ >author);

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

 Example for Pointers to Structure

When the above code is compiled and executed, it produces


the
Bookfollowing result −
title : C Programming
Book author : Nuha Ali
Book subject : C Programming
Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing
Tutorial
Book book_id : 6495700
90
Pointers and Structures

 Functions and Structure

 We will consider four cases here:

– Passing the individual members to functions


– Passing whole structure to functions
– Passing structure pointer to functions
– Passing array of structure to functions

91
Pointers and Structures

 Passing the individual members to functions

 Structure members can be passed to functions as actual


arguments in function call like ordinary variables.

 Problem : Huge number of structure members

 Example : Let us consider a structure employee having


members name, id and salary and pass these members to a
function:

92
Pointers and Structures

display(emp.name,emp.id,emp.salary);

Void display(char e[],int id ,float sal )

printf("nNamettIDttSalaryn);

printf("%st%dt%.2f",e,id,sal);

93
Pointers and Structures

 Passing whole structure to functions


 Whole structure can be passed to a function by the syntax:

function_name(structure_variable_name);

 The called function has the form:

return_type function_name(struct tag_name


structure_variable_name)

… … … … …;
94

}
Pointers and Structures

display(emp);

void display(struct employee e)

printf("nNametIDtSalaryn");

printf("%st%dt%.2f",e.name,e.id,e.salar);

95
Pointers and Structures

 Passing structure pointer to functions

 In this case, address of structure variable is passed as an actual


argument to a function.

 The corresponding formal argument must be a structure type


pointer variable.

 Note: Any changes made to the members in the called function are
directly reflected in the calling function.

96
Pointers and Structures

display(&emp);

void display(struct employee *e)

printf("nNametIDtSalaryn");

printf("%st%dt%.2f",e->name,e->id,e->salary);

97
Pointers and Structures

 Passing array of structure to functions

 Passing an array of structure type to a function is similar to passing


an array of any type to a function.

 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.

 Note: The function prototype comes after the structure definition.


49 Passing array of structures to function

98
Pointers and Structures

display(emp); // emp is array name of size 2


void display(struct employee ee[])
{
int i;
printf("n Namett IDtt Salary\n");
for(i=0;i<2;i++)
{
printf("%stt%dtt%.2fn",ee[i].name,ee[i].id,ee[i].salary);
}
}
99
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

store the next field in the next word.


Pointers and Structures

Self Assessment Question


#include <stdio.h>
void foo(int*);
1. What is the output of this C code?
int main()
{
A. 10 int i = 10;
B. Some garbage value foo((&i)++);
}
C. Compile time error void foo(int *p)
D. Segmentation fault/code crash {
printf("%d\n", *p);
}
Answer: Compile time error

101
Pointers and Structures

Self Assessment Question

2. What is the output of this C code?

#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

Self Assessment Question

3. What is the output of this C code?


#include <stdio.h>
int main()
A. Compile time error {
B. 10 10 int i = 11;
int *p = &i;
C. Undefined behaviour
foo(&p);
D. 10 11 printf("%d ", *p);
}
void foo(int *const *p)
Answer: Compile time error {
int j = 10;
*p = &j;
printf("%d ", **p);
}

103
Pointers and Structures

Self Assessment Question

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

Self Assessment Question

5. Which of the following are themselves a collection of different data types?

A. string
B. structures
C. char
D. all of the mentioned

Answer: structures

105
Pointers and Structures

Self Assessment Question

6. Which operator connects the structure name to its member name?

A. –
B. <-
C. .
D. Both <- and .

Answer: .

106
Pointers and Structures

Self Assessment Question

7. Which of the following structure declaration will throw an error?

A. struct temp{}s;
main(){}
B. struct temp{};
struct temp s;
main(){}
C. struct temp s;
struct temp{};
main(){}
D. None of the mentioned

Answer: None of the mentioned 107


Pointers and Structures

Self Assessment Question

8. What is the output of this C code?.


#include <stdio.h>
struct student
A. Nothing {
B. hello int no;
char name[20];
C. Compile time error };
D. Varies void main()
{
Answer: Compile time error student s;
s.no = 8;
printf("hello");
}

108
Pointers and Structures

Self Assessment Question

#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

Self Assessment Question

10. Can the above code be compiled successfully?

What will size of(myarray)be?(Assume one character occupies 1 byte)


#include <stdio.h>
A. Yes struct p
B. No {
int k;
C. Depends on the standard char c;
D. Depends on the platform float f;
};
int main()
{
Answer: Depends on the standard struct p x = {.c = 97, .f = 3, .k
= 1};
printf("%f\n", x.f);
}

110
Pointers and Structures

Document Links

Topics URL Notes


https://www.programiz.com/c-
Pointers This link explains what is pointers and explain in detail
programming/c-pointers

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

Topics URL Notes

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

Topics URL Page Number

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

Structures https://www.tutorialspoint.com/cprogramming/cprogramming_tutorial.pdf Page Number 120- Page Number 126

114
Pointers and Structures

Thank you

115

You might also like