[go: up one dir, main page]

0% found this document useful (0 votes)
10 views31 pages

1.5 - Review Structure

The document provides an overview of structures in C programming, explaining their purpose in organizing related data types under a single name for easier management. It covers the definition of structures, accessing their members, and the use of nested structures and arrays of structures to handle multiple instances of data efficiently. Additionally, it includes examples and syntax for defining and initializing structures, as well as practical applications such as searching and sorting data.
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)
10 views31 pages

1.5 - Review Structure

The document provides an overview of structures in C programming, explaining their purpose in organizing related data types under a single name for easier management. It covers the definition of structures, accessing their members, and the use of nested structures and arrays of structures to handle multiple instances of data efficiently. Additionally, it includes examples and syntax for defining and initializing structures, as well as practical applications such as searching and sorting data.
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/ 31

Structures in C

Dr. Tanvir Ahmed


Let us discuss some situations
• How would you store a date that has day, month,
and year?
• How would you store 100 different dates?
• How would you store a student’s id, name, and
gpa?
• Now, how would you store the same information
for 100 students?
• So far whatever we have learned, we will
probably use 3 arrays one for ids (int), one for
names (char 2D array), and one for gpas(float).
What is Structure?
• We have used array for various purposes in our codes
so far.
– In an array we can store only same types of data
– For example, it can be either an int array, or float array, or
char array. We cannot mix data type in an array
– Moreover, if you want to keep track of multiple information
of an entity, we might declare multiple arrays.
• For example, if you want to store student ids an integer array, student
names a 2D char array, students grades for 3 courses would be a 2D
float array.
• We keep track all of these arrays using index. For example, index zero
to all the array belongs to student 0, index 1 is for student 1, etc.
– Use of structure can help us to keep them in together more
organized way
What is Structure?
• A structure is a collection of one or more
variables, possibly of different types, grouped
together under a single name for convenient
handling.
• We can make our custom data type using
structure and declare variable of that data type!
• Structures help to organize complicated data,
particularly in large programs, because they
permit a group of related variables to be treated
as a unit instead of separate entities.
What is Structure?
• For example, a ‘book’ is a collection of things such as
title, author, publisher, number of pages, date of
publication, ISBN number, price, etc.
• As you can see all this data is dissimilar, for example,
author is a string, whereas number of pages is an
integer and price is float. For dealing with such
collection, we use structures.
• Each independent element or variable in a structure
is referred to as “member” or “field” of that
structure.
Defining Structure
• Syntax for defining a structure:
struct structure_name{
member1;
member2;
…………………
…………………
memberN;
}variable_names;
• The keyword struct tells the compiler that a structure type is
being defined.
• The structure_name is essentially the type name of the
structure, and the variable_names is where actual instances
of the structure are declared.
• The variable_names part is optional as you can declare the
variable later.
Example of Defining Structure
• Example:
struct book {
char title[40]; /*author name*/
char author[40]; /*book title*/
char pub[40]; /*publisher*/
float price; /*book price*/
int pages; /*no of pages*/
}b1, b2, b3;
• Here, book is the type name of the structure; it is not the name of a
variable. It is the name of your custom data type/or your structure
• The variables defined by this fragment are b1, b2, b3.
– Three memory locations allocated for b1, b2, and b3.
– Each of them has their own title, author, pub, price and pages members.
• You can and generally will declare structure variable like this:
– struct book b1;
– It is somehow like declaring other variables, but you have to put the
keyword struct before the data type name.
• You will also generally define the structure in the global
space of your code, like just after #define and #include area
of your code, so that all the function of you code know
about the structure definition.
Accessing members of structure variables
• Now, when you declare a structure variable:
• Like other variable a memory location is allocated for
that variable
– Where a structure variable contains a list of members
based on the structure definition.
– Of-course we want to assign data and retrieve data from
the members of a variable.
– To access the member of a structure variable we use dot (.)
operator.
– For example, if you want to assign price 12.5 for b1, you
need to write b1.price = 12.5
• See the example in the next slide
– The example shows, various way of declaring variables of
your structure
– Initializing the members of a structure variable by
• Taking user input
• Or directly assigning a value in the code.
Example 1 Declaring and initializing at the same line Always, use strcpy or
loop to copy string. Do
Declaring another structure variable not just assign!
#include <stdio.h>
#include <string.h> Continuing the code
struct Books {
/* b3 specification */
char title[50];
strcpy( b4.title, "C How to program");
char author[50]; strcpy( b4.author, "Deitel");
float price; b4.price = 50.6;
int pages; b4.pages = 200;
}b1, b2;
int main( ) { /* b2 specification */
strcpy( b2.title, "Programming
struct Books b3 ={"Java how to knights");
program","Deitel", 80.5, 500}; strcpy( b2.author, "Arup Guha");
struct Books b4; b2.price = 25.6;
char x; b2.pages = 300;
printf("Enter book title for b1: ");
printf("Information for b2:\n Name: %s
scanf("%[^\n]s", b1.title);
Auhor: %s Price: %0.2f Pages:
//clearing up the \n from the last input %d\n",b2.title, b2.author, b2.price,
while((x=getchar() != '\n') && x != EOF); b2.pages);
printf("Enter author for b1: ");
scanf("%[^\n]s", b1.author); printf("Information for b3:\n Name: %s
printf("Enter price for b1: "); Auhor: %s Price: %0.2f Pages:
scanf("%f", &b1.price); %d\n",b3.title, b3.author, b3.price,
printf("Enter total pages for b1: "); b3.pages);
scanf("%d", &b1.pages); printf("Information for b4:\n Name: %s
Auhor: %s Price: %0.2f Pages:
printf("Information for b1:\n Name: %s Auhor: %d\n",b4.title, b4.author, b4.price,
b4.pages);
%s Price: %0.2f Pages: %d\n",b1.title,
return 0;
b1.author, b1.price, b1.pages);
}
Example output of the last slide’s code
Alternative Syntax of Defining a structure
• Since it's somewhat cumbersome to type "struct book" every time one
wants a variable of type struct book, a typedef allows us to shorten our
struct definition so that we just have to use the name that we give the
struct and not the keyword struct as well. Here how we'd do it for a struct
book:
typedef struct book {
char title[40]; /*author name*/
char author[40]; /*book title*/
float price; /*book price*/
int pages; /*no of pages*/
}book;//here book is not a variable, but a type. You
can use other name too without writing book! But we use
the same name of the structure in this case.

book b1; // now you don’t have to write struct every


time you declare a variable of type book!
Example of using typedef
typedef struct Book { Book is a type, not a variable. See, how we are
char title[50]; declaring a variable of type Book in the main
char author[50]; function. You can also give another name different
float price; from your structure name if you wish.
int pages;
}Book;
No need to write struct every time!
int main( ) {
All the other syntax are same as the last example
Book b1;
Book b2 ={"Java how to program","Deitel", 80.5, 500};
char x;
printf("Enter book title for b1: ");
scanf("%[^\n]s", b1.title);
while((x=getchar() != '\n') && x != EOF); //clearing up the \n from the last
input
printf("Enter author for b1: ");
scanf("%[^\n]s", b1.author);
printf("Enter price for b1: ");
scanf("%f", &b1.price);
printf("Enter total pages for b1: ");
scanf("%d", &b1.pages);

printf("Information for b1:\n Name: %s Auhor: %s Price: %0.2f Pages:


%d\n",b1.title, b1.author, b1.price, b1.pages);

printf("Information for b2:\n Name: %s Auhor: %s Price: %0.2f Pages:


%d\n",b2.title, b2.author, b2.price, b2.pages);

return 0;
}

Nested Structures
We can nest a structure within a structure, within another structure, which is in still another structure
and so on... This is referred to as Nested Structures.
• The following example shows, a Book has a variable of type Author in it
• An author has a variable of type Date in it.
• You can even declare a variable of each of those structure on your own when needed. Like you can
declare a variable for Date, or Author in your code.
• We have used typedef and without typedef structure for this example to show you the difference of
declaring variable. Otherwise, you can choose whichever way you wish.
• Example:
typedef struct Date
{
int day;
int month;
int year;
}Date;

struct Author{
char authorName[50];
char authorLanguage [50];
Date dob; //Date was typedef so no struct
};
typedef struct Book {
char title[50];
struct Author author; //author is a strucute variable
float price;
int pages;
}Book;
int main( ) {
Example of nested structure Book b1;
typedef struct Date char x;
{ printf("Enter book title: ");
int day; scanf("%[^\n]s", b1.title);
int month; while((x=getchar() != '\n') && x != EOF);
int year; //clearing up the \n from the last input
}Date; printf("Enter author name: ");
scanf("%[^\n]s", b1.author.authorName);
struct Author{ while((x=getchar() != '\n') && x != EOF);
char authorName[50]; //clearing up the \n from the last input
char authorLanguage [50]; printf("Enter author Language: ");
Date dob; //Date was typedef so no scanf("%[^\n]s", b1.author. authorLanguage);
struct printf("Enter price: ");
}; scanf("%f", &b1.price);
typedef struct Book { printf("Enter total pages for b1: ");
char title[50]; scanf("%d", &b1.pages);
struct Author author; //author is
a strucute variable printf("Enter day month and year of birth of
float price; author: ");
int pages; scanf("%d%d%d", &b1.author.dob.day,
}Book; &b1.author.dob.month, &b1.author.dob.year);

printf("Information for b1:\n Name: %s Price:


%0.2f Pages: %d\n",b1.title, b1.price,
b1.pages);
See, how we are accessing the members. printf("Author details for book %s \n",
Use dot (.) to access the members b1.title);
printf("Author Name: %s Language: %s Date of
Birth: %d/%d/%d\n", b1.author.authorName,
b1.author.authorLanguage, b1.author.dob.day,
b1.author.dob.month, b1.author.dob.year);

return 0; }
Array of Structures
• Let’s consider a case where we want 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. books[0] title, author, price, pages
• Example: books[1] title, author, price, pages
typedef struct Book { books[2] title, author, price, pages
char title[50];
books[3] title, author, price, pages
char author[50];
float price; ……
int pages;
……
}Book;
Books[99] title, author, price, pages
Book books[100];

This provides space in memory for 100 structure variables


of type Book.
Example Array of structure
#include <stdio.h> Declaring array of structure. As we have used typedef, no
#include <string.h> need to write struct key word. Otherwise you have to
#define SIZE 3
write struct keyword. Continuation of the code
typedef struct Book {
char title[50]; printf("Displaying the book list:
char author[50]; \n");
float price; for(int i=0; i<SIZE; i++)
int pages; {
}Book; printf("Information for book
int main( ) { %d:\n Name: %s Auhor: %s Price:
Book books[SIZE]; %0.2f Pages: %d\n",i+1,
char x; books[i].title, books[i].author,
books[i].price, books[i].pages);
for(int i=0; i<SIZE; i++) { }
printf("Enter book title for book %d: ", return 0;
i+1); }
scanf("%[^\n]s", books[i].title);
//clearing up the \n from the last input
while((x=getchar() != '\n') && x != EOF);
printf("Enter author for book %d: ", i+1);
scanf("%[^\n]s", books[i].author);
printf("Enter price for book %d: ", i+1);
scanf("%f", &books[i].price);
printf("Enter total pages for book %d: ",
i+1);
scanf("%d", &books[i].pages);
while((x=getchar() != '\n') && x != EOF);
//clearing up the \n from the last input
}
Example output of the last slide’s code
Modify the last code to add the
following features
• As you already have an array of books, you can
process it for various purposes:
– Search for books by same authors and display the
details of the book
– Show the book with maximum price
– Show the book with highest number of pages.
– You can even sort the book based on a specific
criteria
– Try them, they are very similar to accessing an
array!
Example: Finding all the books of an
author
char search_key[50];
printf("Enter author name to search: ");
scanf("%[^\n]s",search_key);

for(int i=0; i<SIZE; i++)


{
if(strcmp(books[i].author, search_key) == 0)
{
printf("Book %d:\n", i+1);
printf("Name: %s\n", books[i].bookName);
printf("author name: %s\n", books[i].author);

printf("price: %f\n", books[i].price);


printf("pages: %d\n", books[i].pages);
printf("===========\n");
}
}
Structures and Functions
• Like an ordinary variable, a structure variable can
be passed to a function.
• We may either pass individual structure elements
or the entire structure variable at one go.
• Passing individual elements would become more
tedious as the number of structure elements go
on increasing. So, better approach is to pass the
entire structure variable at a time.
Structures and Functions
• Example 1: Passing individual structure members
struct book{
char title[40];
char author[40]; This parameter list has no
int price; idea about the structure. It
}; can just take two char
void display(char *t, char *a, int p) pointers and one int
{
printf(“\n%s %s %d”,t, a, p);
}

Here, we are not really passing


a structure. Just passing
int main(){ individual members
struct book b1={“Programming knights”,”Arup Guha”,50};

display(b1.title, b1.author, b1.price);


}
Structures and Functions
• Example 2: Passing entire structure variable
struct book{
char title[40]; This function takes a book
char author[40]; structure variable.
int price; Just a note: structures are
}; passed by value like other
types of variables.
void display(struct book b)
{
printf(“\n%s %s %d”,b.title,b.author,b.price);
}

main(){
struct book b1={“Programming knights”,”Arup
Guha”,50};
Here, we are passing our
display(b1); structure variable.
} Note: we are not passing
reerence
Struct and Pointer
struct employee {
char[20] name;
double salary;
int empID;
};
• Now, to declare a variable of this declared type, we write:
struct employee officeworker;
• Often times, for efficiency purposes, it's easier to declare pointers to structs and use those to
manipulate the structures formed.
• Consider the following:
struct employee *temp;// declare a pointer of type employee
temp = &officeworker; //store the address of office worker to temp
(*temp).salary = 50000; //dereference temp to access salary of officeworker
• Since expressions similar to the last one are used so often, there is a shorthand to access a
field/member of a record through a pointer to that record. The last statement can also be
written as:
temp->salary = 50000 // -> is mostly used to dereference structure pointer.
• Another reason to use a pointer to a struct is to dynamically allocate the memory for the
struct. (We will briefly discuss about dynamic memory allocation in our next class).
• This allows the memory to be allocated beyond the “life”/”scope” of the function within
which it was declared. 23
Pointers and Structures

temp
typedef struct bookRec{
float price;
char name[7];
}Book;

main() {
Book temp;

scanf("%d %s", &temp.price, temp.name);


}

24
Pointers and Structures

aPtr
temp
typedef struct bookRec{
float price;
char name[7];
}Book;
main()
{
Book *aPtr;
Book temp;
aPtr = &temp;
scanf("%d %s", &(aPtr->price), aPtr->name);
}
25
More example on accessing Structure Variables

• Structure elements can be accessed through a pointer


to a structure using the arrow (->) operator.
• Example:
struct book{
char title[40];
char author[40];
int price;
};
main(){
struct book b1={“Programming knights”,”Arup
Guha”,125};
struct book *ptr;
ptr=&b1;
printf(“Title:%s, Author:%s, Price:%d”, ptr->title,
ptr->author, ptr->price);
} Output:
Title: Programming Knights, Author: Arup Guha, Price: 125
Passing reference to a structure in function
struct book{
char title[40];
char author[40];
int price; This function takes address
}; of a book structure variable.
This function has the ability
to change the value of b1.
void display(struct book *b)
{
printf(“\n%s %s %d”,b->title,b->author,b->price);
}

main(){
struct book b1={“Programming knights”,”Arup
Guha”,50};
Here, we are passing our
display(&b1); structure variable.
} Note: we are not passing
reerence
Returning a structure from a function
struct point{
int x;
This function returns a point
int y;
type data
};

struct point get()


{
struct point p;
scanf(“%d %d”, &p.x, &p.y);
return p;
}

main(){
struct point p1, p2;
p1 = get();//calling get() function and storing the result in p1
p2 = get();

}
Self-Referential Structures
• It is sometimes desirable to include within a
structure one member that is a pointer to the parent
structure type. Such structures are known as self-
referential structures.
• Example:
struct emp{
char name[40];
struct emp *next;
};
• This is a structure of type emp.
• The structure contains two members:
– 40 element character array, called name,
– and a pointer to a structure of the same type (i.e., a pointer to a structure of type emp),
called next.
• Therefore, this is a self-referential structure.
Self-Referential Structures
• Self-referential structures are very useful in applications that
involve linked data structures, such as lists and trees.
• The basic idea of a linked data structure is that each
component within the structure includes a pointer indicating
where the next component can be found. Therefore, the
relative order of the components can easily be changed
simply by altering the pointers. In addition, individual
components can easily be added or deleted, again by altering
the pointers.
• An example of linked data structure is shown bellow:
Additional notes on Structure before
you start doing the exercise
• The Structure members are stored together in the memory
one after another according to the sequence of their
declaration inside the structure.
• The best way to know the size of your structure is using the
sizeof() function. Just adding the variable sizes inside the
structure is not enough to know the size as the operating
system can add additional memory for the structure to
efficiently access it.
• We can assign a struct variable to another variable of the
same type. When we assign a struct variable to another, all
members of the variable are copied to the other struct
variable. Even if you have an array inside your structure, the
assigned structure will have its own copy of the array.
• For example:
• book b1={“Programming knights”,”Arup Guha”,125};
• If you write,
book b2 = b1; //it will copy the data from b1 and will
maintain a separate copy of the array and other members in
b2.

You might also like