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. The
format of the struct statement is as follows:
struct student
{
int a;
char b[10];
Syntax }
a = 10;
Example b = “Hello”;
C Variable:
Syntax: int a;
int Example: a = 20;
Syntax: char b;
char Example: b=’Z’;
C Array:
Syntax: int a[3];
Example:
a[0] = 10;
a[1] = 20;
a[2] = 30;
int a[3] = ‘\0’;
Syntax: char b[10];
Example:
char b=”Hello”;
Accessing Accessing
structure membe structure membe
rs using normal rs using pointer
variable: variable:
report.mark; report -> mark;
report.name; report -> name;
report.average; report -> average;
1 #include <stdio.h>
2 #include <string.h>
3
4 struct student
5
{
6
7 int id;
8 char name[20];
9 float percentage;
1 };
0
1 int main()
1 {
1 struct student record = {0};
2
1 //Initializing to null
3
1 record.id=1;
4 strcpy(record.name, "Raju");
1 record.percentage = 86.5;
5
1 printf(" Id is: %d \n", record.id);
6
1
7
1
8 printf(" Name is: %s \n",
1 record.name);
9
printf(" Percentage is: %f \n",
2
0 record.percentage);
2 return 0;
1}
2
2
2
3
#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 −
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
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student record2 = {2, "Mani", 93.5};
printf("Records of STUDENT1: \n");
printf(" Id is: %d \n", record1.id);
printf(" Name is: %s \n", record1.name);
printf(" Percentage is: %f \n\n", record1.percentage);
printf("Records of STUDENT2: \n");
printf(" Id is: %d \n", record2.id);
printf(" Name is: %s \n", record2.name);
printf(" Percentage is: %f \n\n", record2.percentage);
return 0;
}
OUTPUT:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
Records of STUDENT2:
Id is: 2
Name is: Mani
Percentage is: 93.500000
C – Array of Structures
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record[60];
Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000
#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( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* 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;
/* print Book1 info */
printBook( Book1 );
/* Print Book2 info */
printBook( Book2 );
return 0;
}
Nested Structures
1. #include <stdio.h>
2. #include <string.h>
3. struct Employee
4. {
5. int id;
6. char name[20];
7. struct Date
8. {
9. int dd;
10. int mm;
11. int yyyy;
12. }doj;
13. }e1;
14. int main( )
15. {
16. //storing employee information
17. e1.id=101;
18. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
19. e1.doj.dd=10;
20. e1.doj.mm=11;
21. e1.doj.yyyy=2014;
22.
23. //printing first employee information
24. printf( "employee id : %d\n", e1.id);
25. printf( "employee name : %s\n", e1.name);
26. printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1
.doj.yyyy);
27. return 0;
28. }
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014
Pointers to Structures
You can define pointers to structures in the same way as you define pointer to any
other variable −
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 the → operator as follows −
struct_pointer->title;
#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( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* 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;
/* print Book1 info by passing address of Book1 */
printBook( &Book1 );
/* print Book2 info by passing address of Book2 */
printBook( &Book2 );
return 0;
}
void printBook( struct Books *book ) {
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
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
Bit Fields
Bit Field Declaration
The declaration of a bit-field has the following form inside a structure −
struct {
};
1
type
2
member_name
3
width
The number of bits in the bit-field. The width must be less than or equal
to the bit width of the specified type.
The variables defined with a predefined width are called bit fields. A bit
field can hold more than a single bit; for example, if you need a variable
to store a value from 0 to 7, then you can define a bit field with a width of
3 bits as follows −
struct {
struct {
} status;
If you are using such variables inside a structure then you can define the
width of a variable which tells the C compiler that you are going to use
only those number of bytes. For example, the above structure can be re-
written as follows −
struct {
} status;
If you will use up to 32 variables each one with a width of 1 bit, then also
the status structure will use 4 bytes. However as soon as you have 33
variables, it will allocate the next slot of the memory and it will start
using 8 bytes. Let us check the following example to understand the
concept −
#include <stdio.h>
#include <string.h>
struct {
} status1;
struct {
} status2;
int main( ) {
return 0;
When the above code is compiled and executed, it produces the following
result −
Memory size occupied by status1 : 8
Memory size occupied by status2 : 4
int main()
{
printf("Size of date is %d bytes\n", sizeof(struct date));
struct date dt = {31, 12, 2014};
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
Output:
unsigned int y;
};
int main()
{
printf("Size of date is %d bytes\n", sizeof(struct date));
struct date dt = {31, 12, 2014};
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}
Output:
Date is 31/12/2014
struct {
};
#include <stdio.h>
#include <stdlib.h>
struct person {
int age;
float weight;
char name[30];
};
int main()
{
struct person *ptr;
int i, num;
printf("Enter number of persons: ");
scanf("%d", &num);
printf("Displaying Infromation:\n");
for(i = 0; i < num; ++i)
printf("%s\t%d\t%.2f\n", (ptr+i)->name, (ptr+i)->age,
(ptr+i)->weight);
return 0;
}
Output
Enter number of persons: 2
Enter name, age and weight of the person respectively:
Adam
2
3.2
Enter name, age and weight of the person respectively:
Eve
6
2.3
Displaying Information:
Adam 2 3.20 Eve 6 2.30
Unions
A union is a special data type available in C that allows to store different data
types in the same memory location. You can define a union with many members,
but only one member can contain a value at any given time. Unions provide an
efficient way of using the same memory location for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as
you did while defining a structure. The union statement defines a new
data type with more than one member for your program. The format of
the union statement is as follows −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %d\n",
sizeof(data));
return 0;
}
When the above code is compiled and executed, it produces the following
result −
Memory size occupied by data : 20
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following
result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got
corrupted because the final value assigned to the variable has occupied
the memory location and this is the reason that the value of str member
is getting printed very well.
Now let's look into the same example once again where we will use one
variable at a time which is the main purpose of having unions −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a time.
// Or
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
Output:
2
In the above example, we declared “day” as the variable and the value of “Wed” is allocated to day, which is 2.
So as a result, 2 is printed.
Another example of enumeration is:
int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
return 0;
}
Output:
0 1 2 3 4 5 6 7 8 9 10 11
In this example, the for loop will run from i = 0 to i = 11, as initially the value of i is Jan which is 0 and the
value of Dec is 11.
int main()
{
printf("%d, %d, %d", Working, Failed, Freezed);
return 0;
}
Output:
1, 0, 0
2. If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0.
For example, in the following C program, sunday gets value 0, monday gets 1, and so on.
#include <stdio.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum day d = thursday;
printf("The day number stored in d is %d", d);
return 0;
}
Output:
The day number stored in d is 4
3. We can assign values to some name in any order. All unassigned names get value as value of previous name
plus one.
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5,
wednesday, thursday = 10, friday, saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,
wednesday, thursday, friday, saturday);
return 0;
}
Output:
1 2 5 6 10 11 12
4. The value assigned to enum names must be some integeral constant, i.e., the value must be in
range from minimum possible integer value to maximum possible integer value.
5. All enum constants must be unique in their scope. For example, the following program fails in
compilation.
Output:
Compile Error: 'failed' has a previous declaration as 'state failed'
Exercise:
Predict the output of following C programs
Program 1:
#include <stdio.h>
enum day {sunday = 1, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum day d = thursday;
printf("The day number stored in d is %d", d);
return 0;
}
Program 2:
#include <stdio.h>
enum State {WORKING = 0, FAILED, FREEZED};
enum State currState = 2;
int main() {
(FindState() == WORKING)? printf("WORKING"): printf("NOT WORKING");
return 0;
}
typedef in C
typedef keyword is used to assign a new name to a type. This is used just to prevent us from writing
more.
For example, if we want to declare some variables of type unsigned int, we have to write unsigned
int in a program and it can be quite hectic for some of us. So, we can assign a new name of our
choice for unsigned int using typedef which can be used anytime we want to use unsigned int in a
program.
Now, we can write uint in the whole program instead of unsigned int. The above code is the same as
writing:
unsigned int i, j;
Let's see an example.
#include <stdio.h>
int main() {
typedef unsigned int ui;
ui i = 5, j = 8;
printf("i = %d\n", i);
printf("j = %d\n", j);
return 0;
}
Output
i=5
j=8