0% found this document useful (0 votes)
21 views46 pages

Structure

The document discusses the concept of structures in C programming, which allow for the grouping of different data types into a single entity. It explains how to declare structures, access their elements, and use them in arrays, along with dynamic memory allocation techniques. Additionally, it covers advanced topics such as nested structures, self-referential structures, and the use of pointers with structures.

Uploaded by

bk5721333
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)
21 views46 pages

Structure

The document discusses the concept of structures in C programming, which allow for the grouping of different data types into a single entity. It explains how to declare structures, access their elements, and use them in arrays, along with dynamic memory allocation techniques. Additionally, it covers advanced topics such as nested structures, self-referential structures, and the use of pointers with structures.

Uploaded by

bk5721333
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/ 46

CSCI-101

Computer Fundamentals and C


Programming
Structure
Dr. Kunwar Pal
Dept. of CSE
NIT Jalandhar

"Structure" Dr. Kunwar Pal, CSED, NITJ 1


Introduction
We have seen earlier how ordinary variables can hold one
piece of information and how arrays can hold a number of
pieces of information of the same data type.
These two data types can handle a great variety of situations.
But quite often we deal with entities that are collection of
dissimilar data types.
For example, suppose you want to store data about a book.
You might want to store its name (a string), its price (a float)
and number of pages in it (an int).
If data about say 3 such books is to be stored, then we can
follow two approaches:
1. Construct individual arrays, one for storing names, another for storing prices and still another for
storing number of pages.
2. Use a structure variable

"Structure" Dr. Kunwar Pal, CSED, NITJ 2


Method-1: Using Array

"Structure" Dr. Kunwar Pal, CSED, NITJ 3


Output

"Structure" Dr. Kunwar Pal, CSED, NITJ 4


This approach no doubt allows you to store names, prices and
number of pages.
The program becomes more difficult to handle as the number of
items relating to the book go on increasing.
For example, we would be required to use a number of arrays, if
we also decide to store name of the publisher, date of purchase
of book, etc.
To solve this problem, C provides a special data type—the
structure.

"Structure" Dr. Kunwar Pal, CSED, NITJ 5


Method-2: Structure
A structure contains a number of data types grouped together.
These data types may or may not be of the same type.
The following example illustrates the use of this data type.

"Structure" Dr. Kunwar Pal, CSED, NITJ 6


Output

"Structure" Dr. Kunwar Pal, CSED, NITJ 7


Previous program demonstrates two fundamental aspects of
structures:
(a) declaration of a structure
(b) accessing of structure elements

Let us discuss at these concepts one by one.

"Structure" Dr. Kunwar Pal, CSED, NITJ 8


Declaring a Structure
struct book
{
char name ;
float price ;
int pages ;
};

This statement defines a new data type called struct book.


Each variable of this data type will consist of a character
variable called name, a float variable called price and an
integer variable called pages.

"Structure" Dr. Kunwar Pal, CSED, NITJ 9


General form of a structure
declaration
struct <structure name>
{
structure element 1 ;
structure element 2 ;
structure element 3 ;
......
......
};

▪ Once the new structure data type has been defined one or more
variables can be declared to be of that type.
▪ For example the variables b1, b2, b3 can be declared to be of the
type struct book, as,

struct book b1, b2, b3 ;

"Structure" Dr. Kunwar Pal, CSED, NITJ 10


Memory Allocation
This statement (struct book b1) sets aside space in memory.
It makes available space to hold all the elements in the
structure—
in this case, 7 bytes—one for name, four for price and two for
pages.
These bytes are always in adjacent memory locations.

"Structure" Dr. Kunwar Pal, CSED, NITJ 11


we can combine the declaration of the structure type and the structure
variables in one statement

"Structure" Dr. Kunwar Pal, CSED, NITJ 12


initialization
Like primary variables and arrays, structure variables can also
be initialized where they are declared.
The format used is quite similar to that used to initiate arrays.

◦ struct book
{
char name[10] ;
float price ;
int pages ;
};

struct book b1 = { "Basic", 130.00, 550 } ;
struct book b2 = { "Physics", 150.80, 800 } ;

"Structure" Dr. Kunwar Pal, CSED, NITJ 13


Important Points
The closing brace in the structure type declaration must be
followed by a semicolon.
It is important to understand that a structure type declaration
does not tell the compiler to reserve any space in memory.
All a structure declaration does is, it defines the ‘form’ of the
structure.
Usually structure type declaration appears at the top of the
source code file, before any variables or functions are defined.
In very large programs they are usually put in a separate
header file, and the file is included (using the preprocessor
directive #include) in whichever program we want to use this
structure type.

"Structure" Dr. Kunwar Pal, CSED, NITJ 14


Accessing Structure Elements
In arrays we can access individual elements of an array using a
subscript.
Structures use a different scheme.
They use a dot (.)operator.
So to refer to pages of the structure defined in our sample
program we have to use, b1.pages
Similarly, to refer to price we would use, b1.price
Note that before the dot there must always be a structure
variable and after the dot there must always be a structure
element.

"Structure" Dr. Kunwar Pal, CSED, NITJ 15


Memory map of structure elements
Example:
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1 = { 'B', 130.00, 550 } ;

"Structure" Dr. Kunwar Pal, CSED, NITJ 16


Array of Structures
In our sample program, to store data of 100 books we would
be required to use 100 different structure variables from b1 to
b100, which is definitely not very convenient.
A better approach would be to use an array of structures.
Following program shows how to use an array of structures.

"Structure" Dr. Kunwar Pal, CSED, NITJ 17


Array of structures
main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b[100] ;
int i ;
for ( i = 0 ; i <= 99 ; i++ )
{
printf ( "\nEnter name, price and pages " ) ;
scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;
}
for ( i = 0 ; i <= 99 ; i++ )
printf ( "\n%c %f %d", b[i].name, b[i].price, b[i].pages ) ;
}

"Structure" Dr. Kunwar Pal, CSED, NITJ 18


Discussion about the program:
Notice how the array of structures is declared “struct book b[100] ;”
This provides space in memory for 100 structures of the type struct book.
The syntax we use to reference each element of the array b is similar to the
syntax used for arrays of ints and chars.
For example, we refer to zeroth book’s price as b[0].price.
Similarly, we refer first book’s pages as b[1].pages.
In an array of structures all elements of the array are stored in adjacent
memory locations.
Since each element of this array is a structure, and since all structure
elements are always stored in adjacent locations you can very well
visualize the arrangement of array of structures in memory.
In our example, b[0]’s name, price and pages in memory would be
immediately followed by b[1]’s name, price and pages, and so on.

"Structure" Dr. Kunwar Pal, CSED, NITJ 19


Additional Features of Structures
The values of a structure variable can be assigned to another structure
variable of the same type using the assignment operator.
main( )
e2.salary = e1.salary ;
{
/* copying all elements at one go */
struct employee
e3 = e2 ;
{
printf ( "\n%s %d %f", e1.name,
char name[10] ;
e1.age, e1.salary ) ;
int age ;
printf ( "\n%s %d %f", e2.name,
float salary ;
e2.age, e2.salary ) ;
};
printf ( "\n%s %d %f", e3.name,
struct employee e1 = { "Sanjay", 30, 5500.50 } ;
e3.age, e3.salary ) ;
struct employee e2, e3 ;
}
/* piece-meal copying */
strcpy ( e2.name, e1.name ) ;
e2.age = e1.age ;

"Structure" Dr. Kunwar Pal, CSED, NITJ 20


output
The output of the program would be...
Sanjay 30 5500.500000
Sanjay 30 5500.500000
Sanjay 30 5500.500000

"Structure" Dr. Kunwar Pal, CSED, NITJ 21


Nested Structure
One structure can be nested within another structure. Using this facility complex
data types can be created. The following program shows nested structures at work.
main( )
{
struct address
{
char phone[15] ;
char city[25] ;
int pin ;
};

struct emp
{
char name[25] ;
struct address a ;
};

"Structure" Dr. Kunwar Pal, CSED, NITJ 22


Program Cont..
struct emp e = { "jeru", "531046", "nagpur", 10 };
printf ( "\nname = %s phone = %s", e.name, e.a.phone ) ;
printf ( "\ncity = %s pin = %d", e.a.city, e.a.pin ) ;

} (Close Main Function)

OUTPUT:
name = jeru phone = 531046
city = nagpur pin = 10

"Structure" Dr. Kunwar Pal, CSED, NITJ 23


Discussion about Program
Notice the method used to access the element of a structure that is
part of another structure.
For this the dot operator is used twice, as in the expression,
e.a.pin or e.a.city
Of course, the nesting process need not stop at this level.
We can nest a structure within a structure, within another
structure, which is in still another structure and so on... till the
time we can comprehend the structure ourselves.
Such construction however gives rise to variable names that can be
surprisingly self descriptive,
for example:
“maruti.engine.bolt.large.qty”

"Structure" Dr. Kunwar Pal, CSED, NITJ 24


Passing individual structure elements in
Function
main( )
{ OUTPUT:
struct book
{ Let us C YPK 101
char name[25] ;
char author[25] ;
int callno ;
};
struct book b1 = { "Let us C", "YPK", 101 } ;
display ( b1.name, b1.author, b1.callno ) ;
}

display ( char *s, char *t, int n )


{
printf ( "\n%s %s %d", s, t, n ) ;
}

"Structure" Dr. Kunwar Pal, CSED, NITJ 25


Discussion about Program
Observe that in the declaration of the structure, name and
author have been declared as arrays.
Therefore, when we call the function display( ) using,
display ( b1.name, b1.author, b1.callno ) ;
we are passing the base addresses of the arrays name and
author, but the value stored in callno.
Thus, this is a mixed call—a call by reference as well as a call
by value.

"Structure" Dr. Kunwar Pal, CSED, NITJ 26


Passing entire structure variable
in Function
struct book
{ char name[25] ;
char author[25] ;
int callno ;
};
main( )
{ struct book b1 = { "Let us C", "YPK", 101 } ;
display ( b1 ) ;
}

display ( struct book b )


{
printf ( "\n%s %s %d", b.name, b.author, b.callno ) ;
}

And here is the output...


Let us C YPK 101

"Structure" Dr. Kunwar Pal, CSED, NITJ 27


structure pointers
main( )
{
struct book
{
char name[25] ;
char author[25] ;
int callno ;
};
struct book b1 = { "Let us C", "YPK", 101 } ;
struct book *ptr ;
ptr = &b1 ;
printf ( "\n%s %s %d", b1.name, b1.author, b1.callno ) ;
printf ( "\n%s %s %d", ptr->name, ptr->author, ptr->callno ) ;
}

"Structure" Dr. Kunwar Pal, CSED, NITJ 28


Discussion
The first printf( ) is as usual.
The second printf( ) however is peculiar.
We can’t use ptr.name or ptr.callno because ptr is not a structure variable
but a pointer to a structure, and the dot operator requires a structure
variable on its left.
In such cases C provides an operator ->, called an arrow operator to refer to
the structure elements.
Remember that on the left hand side of the ‘.’ structure operator, there must
always be a structure variable, whereas on the left hand side of the ‘->’
operator there must always be a pointer to a structure.
The arrangement of the structure variable and pointer to structure in
memory is shown in next slide.

"Structure" Dr. Kunwar Pal, CSED, NITJ 29


"Structure" Dr. Kunwar Pal, CSED, NITJ 30
Self-Referential Structures
▪ Structure that contains a pointer to a structure of the same type
▪ Can be linked together to form useful data structures such as lists, queues,
stacks and trees
▪ Terminated with a NULL pointer (0)
struct node {
int data;
struct node *nextPtr; //Self Referential
}
▪ nextPtr
▪ Points to an object of type node
▪ Referred to as a link
▪ Ties one node to another node

"Structure" Dr. Kunwar Pal, CSED, NITJ 31


Two self-referential structures linked
together

"Structure" Dr. Kunwar Pal, CSED, NITJ 32


Dynamic Memory Allocation
The process of allocating memory at run time is known as
dynamic memory allocation.
There are four library routines known as memory management
functions that can be used for allocating and freeing memory
during execution.
malloc(), calloc(), free(), realloc()
All are defined in alloc.h

"Structure" Dr. Kunwar Pal, CSED, NITJ 33


Malloc
malloc: Allocating a block of memory
General form
▪ ptr = (cast-type *) malloc(byte-size);
▪ ptr is a pointer of type cast-type
▪ The malloc() returns a pointer (of cast-type) to an area of memory with size byte-size.
▪ If there is not enough space a NULL pointer is returned.

Example
▪ x=(int *) malloc(100*sizeof(int));
▪ cptr=(char *) malloc(10);
▪ st= (struct *) malloc(sizeof(struct store));

❑ Storage space allocated dynamically has no name and therefore its contents can be
accessed only through a pointer.

"Structure" Dr. Kunwar Pal, CSED, NITJ 34


calloc
calloc: Allocating multiple block of memory
While malloc() allocates a single block of storage space,
calloc() allocates multiple blocks of storage, each of the same
size, and then set all bytes to zero.
If there is not enough space a NULL pointer is returned.
◦ General form
◦ ptr=(cast-type *) calloc(n, element-size);

"Structure" Dr. Kunwar Pal, CSED, NITJ 35


Free
free( ); Releasing the used space
With dynamic run-time allocation, we need to release the
space when it is not required
◦ free(ptr);
◦ Frees previously allocated space created by malloc() or calloc()

"Structure" Dr. Kunwar Pal, CSED, NITJ 36


realloc
realloc( );
Altering the size of a block
It is likely that the previous allocated memory is not sufficient and
we need additional space for more elements.
It is also possible that the memory allocated is much larger than
necessary and we want to reduce it.
◦ ptr=realloc(ptr, newsize);
◦ Modifies the size of previously allocated space by malloc() or
calloc().

"Structure" Dr. Kunwar Pal, CSED, NITJ 37


typedef
The C programming language provides a keyword called typedef.
We can use typedef to give new name to a data type or we can that
It is used to create a synonymous.
Following is an example to define a term BYTE for one-byte
numbers.
◦ “typedef unsigned char BYTE;”
After this type definitions, the identifier BYTE can be used as an
abbreviation(short name) for the type unsigned char,
for example
◦ “BYTE b1, b2;”

"Structure" Dr. Kunwar Pal, CSED, NITJ 38


Example
struct rect
{
int top ;
int left ;
int right ;
int bottom ;
};
typedef struct rect RECT ;
typedef struct rect* PRECT ;

"Structure" Dr. Kunwar Pal, CSED, NITJ 39


What have we achieved out of this? It makes user-defined data
types like structures look, act and behave similar to standard
data types like integers, floats, etc.
You would agree that the following declarations
RECT r ;
int i ;
are more logical than
struct RECT r ;
int i ;

"Structure" Dr. Kunwar Pal, CSED, NITJ 40


Union
A union is declared using the keyword union as:
union student
{
int roll_no;
char section[2];
};
union student s;

"Structure" Dr. Kunwar Pal, CSED, NITJ 41


Both structure and unions are used to group a number of different
variables together.
Syntactically both structure and unions are exactly same. The main
difference between them is in storage.
In structures, each member has its own memory location but all members
of union use the same memory location which is equal to the greatest
member’s size.

"Structure" Dr. Kunwar Pal, CSED, NITJ 42


Structure vs Union

"Structure" Dr. Kunwar Pal, CSED, NITJ 43


#include <stdio.h>
union x
{ int i;
char ch[2];
} key;

int main()
{ key.i=512;
printf(“key.i=%d\n", c.a);
printf(“key.ch[0]=%d\n", c.b[0]);
printf(“key.ch[1]=%d\n", c.b[1]);
return 0;
}

"Structure" Dr. Kunwar Pal, CSED, NITJ 44


Output
Key.i = 512
Key.ch[0] = 0
Key.ch[1] = 2

"Structure" Dr. Kunwar Pal, CSED, NITJ 45


Thanks

Stay home, stay safe, stay healthy

"Structure" Dr. Kunwar Pal, CSED, NITJ 46

You might also like