Defining A Structure: Title Author Subject Book ID
Defining A Structure: Title Author Subject Book ID
Defining A Structure: Title Author Subject Book ID
of the same kind. Similarly structure is another user defined data type
available in C that allows to combine data items of different kinds.
Title
Author
Subject
Book ID
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
member definition;
member definition;
...
member definition;
} [one or more structure variables];
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
Accessing Structure Members
To access any member of a structure, we use the member access
operator (.). The member access operator is coded as a period between
the structure variable name and the structure member that we wish to
access. You would use the keyword struct to define variables of
structure type. The following example shows how to use a structure in a
program
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
return 0;
}
When the above code is compiled and executed, it produces the following
result
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books book );
int main( ) {
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
return 0;
}
When the above code is compiled and executed, it produces the following
result
Pointers to Structures
You can define pointers to structures in the same way as you define
pointer to any other variable