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

Module 9 - Structures

The document discusses structures in C programming. It defines a structure as a group of logically related data items. A structure allows defining a custom data type that bundles together different data types. Structures can be defined globally or locally. Structure members are accessed using the dot operator. Structure variables can be initialized at the time of declaration. The sizeof operator returns the total size of a structure, which may be larger than the sum of sizes of individual members due to padding. Structures help represent complex data in an organized way.

Uploaded by

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

Module 9 - Structures

The document discusses structures in C programming. It defines a structure as a group of logically related data items. A structure allows defining a custom data type that bundles together different data types. Structures can be defined globally or locally. Structure members are accessed using the dot operator. Structure variables can be initialized at the time of declaration. The sizeof operator returns the total size of a structure, which may be larger than the sum of sizes of individual members due to padding. Structures help represent complex data in an organized way.

Uploaded by

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

Module 9 – Structures in C

BITS Pilani Dr. Ashutosh Bhatia & Dr. Asish Bera


Pilani Campus
Department of Computer Science & Information Systems
Module Overview

• Tuple Data
• Structures
• Nested Structures and Array of Structures
• Passing Structure Variables to Functions
• Union
• Enumerator

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Tuple Data
Tuple Data
Consider student database. Every student has a few attributes:
• Name
• ID
• Group

This is known as tuple data where {Name, ID No, Group} is a tuple


Example: The below table contains 3 records of the above tuple type
ID Name Group
0910 Rama Sarma B4
0313 Alex Mathew A8
0542 Vijay Kumar A7

Tuple Data is used in Database Systems

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Representing Tuple Data
First attempt: 3 lists (i.e. arrays)
– Name array, ID array, and Group array.
– Problems: Consider add / delete operations.
• Shifting to be done in 3 arrays separately.
• 3 arrays are the 3 element values passed as
parameters.
• Data representation “does not say” the 3 things are
related.

Better Solution: 1 list of triples


– Each triple is of the form (ID, Name, Group)
– add / delete operation: Shifting for one array only.
• Can use Structures in C to do this.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Structures in C
Structures in C

• Structure
– Group of logically related data items
– Example: ID, Name, Group
• A single structure may contain data of one or more data types
– ID: int ID
– Name: char Name[]
– Group: char Group[]
• The individual structure elements are called members
• We are essentially defining a new data type
• Then we can create variables of the new data type
– These variables can be global, static or auto
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Defining a Structure
struct struct_name { Example: Student structure
member 1; containing ID, Name, Group
member 2;
… struct student {
}; int ID;
char Name[20]; Members
• struct is the required
char Group[3];
keyword
• struct_name is the name of }
the structure
• member 1, member 2, …
are individual member
declarations
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Declaring Variables of the
Structure type
struct struct_name var_1, var_2, …, var_n;

Example 1: Example 2:
struct student { struct book {
int ID; char Name[20];
char Name[20]; float price;
char Group[3]; char ISBN[30];
}; };

// declaring variable of // declaring variable of


// the type struct student // the type struct book
struct student s1, s2; struct book b1, b2;

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Combining Structure Definition
and Variable Definition
struct struct_name{ struct {
data_type member 1; data_type member 1;
data_type member 2; data_type member 2;
… …
}var1, var2, … varn; }var1, var2, … varn;

Example: Example:
struct student { struct {
int ID; int ID;
char Name[20]; char Name[20];
char Group[3]; char Group[3];
} s1, s2; } s1, s2;
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Accessing members of a
structure
• A structure member can be accessed by writing
structure_variable.MemberName

Example: Consider the following structure definition:


struct student {
int ID;
char Name[20];
float Marks[5];
}s1, s2;

s1.Name → Value stored in the Name field of s1 variable


s2.Name → Value stored in the Name field of s2 variable
s2.Marks[i] → Value stored at the ith position of the Marks array of s2
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example
#include main()
{
struct complex {
float real;
float cmplex;
} a, b, c;

scanf (“%f %f”, &a.real, &a.cmplex);


scanf (“%f %f”, &b.real, &b.cmplex);
c.real = a.real + b.real;
c.cmplex = a.cmplex + b.cmplex;
printf (“\n %f + %f j”, c.real, c.cmplex);
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Where can we define
structures?
• Structures can be defined in:
• Global Space
• Outside all function definitions
• Available everywhere inside and outside all functions to
declare variables of its type
• Local Space
• Inside a function
• Variables of this structure type can be declared and
used only inside that function.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Examples
Structure defined in global space: Structure defined in local space:
#include <stdio.h> #include <stdio.h>
struct student{ int f1() {
int ID; struct student{
char Name[20]; int ID;
float marks[5]; char Name[20];
}; float marks[5];
int f1() { };
struct student s1; struct student s3;
… // operations on s1 … // operations on s3
} }
int f2() { int f2() {
struct student s2; // can’t define a variable
… // operations on s2 with struct student here
} }
int main() { int main() {
… …
} }

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Structure Initialization
struct book {
char Name[20];
float price;
char ISBN[30];
};
struct book b1 = {”Book1”, 550.00, ”I1”},
b2 = {”Book2”, 650.00, ”I2”};

b1.Name = Book1 b2.Name = Book2


b1.price = 550.00 b2. price = 650.00
b1.ISBN = I1 b2.ISBN = I2

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
typedef
Allows users to define new data-types
Syntax:
typedef type new-type

Example 1:
typedef int Integer;
Integer I1, I2;

Example 2:
typedef struct{
float real;
• It is a common practice to define
float imag; structures using typedef
} COMPLEX;
• It simplifies the syntax and increases
readability of the program
COMPLEX c1, c2;

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
sizeof() for struct variables
struct test_struct {
short a; //2bytes printf("a= %lu\n", sizeof(test.a)); = 2
int b; //4bytes printf("b= %lu\n", sizeof(test.b)); = 4
char c; //1byte printf("c= %lu\n", sizeof(test.c)); = 1
} test; printf("%lu\n", sizeof(test)); = 12

• We can notice that the sizeof(test) > sizeof(test.a) +


sizeof(test.b) + sizeof(test.c)
• This is because the compiler adds (may add) padding for alignment requirements
• Padding means to append empty locations towards the end (or beginning)
1000 1001 1002 1003
a (1000, 1001) padding 12 contiguous
b (1004, 5, 6, 7) locations in
main memory
C (1008) padding

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Memory view of storing a
struct variable
struct test_struct { Address
short a; //2bytes
int b; //4bytes a (2 bytes) 1000
char c; //1byte 1001
padding (2 bytes)
1002
} test;
1003
1004
b (4 bytes) 1005
1006
1007
c (1 byte)
1008
1009
Note: This illustration considers that each padding (3 bytes) 1010
address is represented by 4 bits. 1011

Also note that in this example int is Total 12


occupying 4 bytes. Some compilers use 2 bytes
bytes for int, and some use 4 bytes.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Another Example
struct test_struct {
char a; //1byte printf("a= %lu\n", sizeof(test.a)); = 1
short b; //2bytes printf("b= %lu\n", sizeof(test.b)); = 2
int c; //4bytes printf("c= %lu\n", sizeof(test.c)); = 4
} test; printf("%lu\n", sizeof(test)); = 8

a (1000) padding (1 byte) b(1002-1003)


c(1004-1007)

• We can notice that the padding added by compiler is less (only 1 byte), for the
same set of variable types, arranged with a different order in the structure.
• The total number of bytes to be added for padding is decided by the compiler
depending upon the arrangement of members inside the structure.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Operations on struct variables

• Unlike arrays, group operations can be performed with structure


variables
• A structure variable can be directly assigned to another structure
variable of the same type
a1 = a2;
The contents of members of a2 are copies to members of a1.
• You can’t do this for two arrays, without using “pointers”
• We will study about pointers in the next module
• You still can’t do equality check for two structure variables, i.e.
if (a1 == a2) is not valid in C
• You shall have to check equality for individual members

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Swap two structure variables
struct book { Output:
char Name[20]; The name of the Book in b1 is Programming
float price; The name of the Book in b2 is Algorithms
char ISBN[30];
};
int main(){
struct book b1 = {”Algorithms”, 550.00, ”I1”};
struct book b2 = {”Programming”, 650.00, ”I2”};
// swapping b1 and b2
struct book b3;
b3 = b1;
b1 = b2;
b2 = b3;
printf(”The name of Book in b1 is %s\n”, b1.Name);
printf(”The name of Book in b2 is %s\n”, b2.Name);
return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Incorrect way of using structure
variables
struct book {
char Name[20];
float price;
char ISBN[30];
};
int main(){
struct book b1 = {”Algorithms”, 550.00, ”I1”};
struct book b2 = {”Programming”, 650.00, ”I2”};
// Incorrect way of using structure variables
// if (b1 == b2)
if(b1.price == b2.price) // Correct way
printf(”Both the books have the same price\n”);
else
printf(”Both the books DON’T have the same price”);
return 0;
} Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Nested Structures and Array of Structures


Nested Structures
struct student{ struct address
float CGPA; {
char dept[10]; int PINCODE;
struct address char city[10];
{ };
int PINCODE; struct student
char city[10]; {
} add; float CGPA;
} s1; char dept[10];
struct address add;
}s1;

To access PINCODE → s1.add.PINCODE


Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example of nested structures
struct address
{
int PINCODE;
char city[10];
};
struct student
{ int main() {
float CGPA; struct student s1;
char dept[10]; s1.add.PINCODE = 333031;
struct address add; s1.add.city = “Vizag”;
}; s1.CGPA = 10.0;
s1.dept = “CS”;
printf(“s1’s city is %s”, s1.add.city);
printf(“s1’s CGPA is %f”, s1.CGPA);
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Array of Structures
Once a structure has been defined, we can declare an array of
structures
Example:
struct book {
char Name[20];
float price;
char ISBN[30];
};
struct book bookList[50];

The individual members can be accessed as:


bookList[i].price → returns the price of the ith book.

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example
Program to store information of 5 students
int main(){
#include <stdio.h> printf(“Enter the details:\n”);
for(i = 0; i < 5; i++)
struct student{ {
char Name[10]; printf(“Enter name\n”);
float CGPA; scanf(“%s”, s[i].name);
float marks[5]; printf(“Enter the marks\n”);
}; for(j = 0; j< 5; j++)
scanf(“%f”,&s[i].marks[j]);
struct student s[5]; printf(“Enter the CGPA\n”);
scanf(“%f”,&s[i].CGPA);
}}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Storing database records in
Array of Structures
• Remember our motivation for structures to store tuple data…

ID Name Group
0910 Rama Sarma B4
0313 Alex Mathew A8
0542 Vijay Kumar A7

• The above table can be stored in a struct student array – arr


• Now its easy to add/delete records:
– Simply create a new variable of the type struct student and append
it to arr
– If the array is sorted on ID numbers, it is sufficient to do necessary shiftings in
arr itself and store the new record in its appropriate position
– Deletion is also similar Refer to slides of Module 8 to understand
add/append/delete in an array.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Passing Structures to Functions


Passing struct variables to
functions
• A structure can be passed as argument to a function

• Structures can be passed both by pass by value and pass by


reference
• We will study about pass by reference later with “pointers”

• A function can also return a structure

• Array of structures are by default passed by reference


• Just like any other arrays.
• We will study later with pointers

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example – Pass by value

#include <stdio.h> cmplx add(cmplx x,cmplx y){


typedef struct { cmplx t;
float re; t.re = x.re + y.re ;
float im; t.im = x.im + y.im ;
} cmplx; return (t) ;
}
int main() { • When the function add() is
cmplx a, b, c; called, the values of the
scanf (”%f %f”, &a.re, &a.im); members of variables a and b
scanf (”%f %f”, &b.re, &b.im); are copied into members of
c = add (a, b) ; variables x and y.
printf (”\n %f %f”, c,re, c.im); • When the function add() returns,
} the values of the members of
variable t are copied into the
members of variable c.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example: Passing structure by
value illustrated
cmplx add(cmplx x,cmplx y) and c = add(a, b);

return (t)
x.re = a.re, x.im = a.im
y.re = b.re, y.im = b.im

c = t
c.re t.re
c.im t.im
t.re x.re + y.re
t.im x.im + y.im

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Previous Example (modified)
Program to store information void computeSum(struct student[], int);
of 5 students, compute total int main(){
marks for each student and printf(“Enter the details:\n”);
print it. for(i = 0; i < 5; i++)
{
#include <stdio.h> printf(“Enter name\n”);
scanf(“%s”, s[i].name);
printf(“Enter the marks\n”);
struct student{
for(j = 0; j< 5; j++)
char Name[10];
scanf(“%f”,&s[i].marks[j]);
float CGPA; printf(“Enter the CGPA\n”);
float marks[5]; scanf(“%f”,&s[i].CGPA);
}; }
computeSum(s,5);
struct student s[5]; }

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example (contd.)
void computeSum(struct student sArr[], int size){
int i,j,sum;
for(i=0;i<size;i++)
{
sum = 0;
for(j=0;j<5;j++)
{
sum += sArr[i].marks[j];
}
printf(“Total marks of %s are %d”, sArr[i].Name, sum);
}
return;
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Enumerator in C
Enumerator in C
• Consider this structure • However, we know that there
definition: are only limited number of
struct student { groups (or disciplines) offered
int ID; in our Campus. They include:-
{A1, A2, A3, A4, A5, A7, A8,
char Name[20]; B1, B2, B3, B4, B5, D2}
char Group[3];
}; • Can we do something to
restrict the values assigned to
• The member Group of the the member Group to always
above structure has been be from the above set?
declared as a character
array of 3 characters, which • enum is the solution!
can take any values.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Enumerator in C
typedef enum {A1,A2,A3,A4,A5,A7,A8,B1,B2,B3,B4,B5,D2}
Group_lbl;

New definition to struct student:


struct student {
int ID;
char Name[20];
Group_lbl Group;
};
Now the member variable Group can take a value only from the above list.
Each Value inside enum is actually an integer, i.e., A1=0, A2=1, … and so on.
We can check by printing them using %d.
We can also assign custom numbers to each of the values of enum, like:-
typedef enum {A1=1,A2=2,A3=5,A4=10,…} Group_lbl;
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example
typedef enum {A1,A2,A3,A4,A5,A7,A8,B1,B2,B3,B4,B5,D2}
Group_lbl;

struct student {
int ID;
char Name[20];
Group_lbl Group;
};
int main(){
struct student s1 = {876, “Karthik”, A1};
struct student s2;
s2.ID = 233;
s2.Name = “Ganesh”;
s2.Group = B5;
if(s2.Group == B5) printf(“s2 is studying Physics”);
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

You might also like