KEMBAR78
C Structure, Union, Enum | PDF | Pointer (Computer Programming) | Data Type
0% found this document useful (0 votes)
6 views11 pages

C Structure, Union, Enum

C structures are user-defined data types that group different types of data into a single type, allowing for organized data management. They can be declared, defined, and initialized in various ways, and are useful for representing complex data like students or books. However, C structures have limitations such as higher memory consumption and lack of data hiding, while unions allow for storing different data types in the same memory location, with only one member being active at a time.

Uploaded by

Prajukta Das
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)
6 views11 pages

C Structure, Union, Enum

C structures are user-defined data types that group different types of data into a single type, allowing for organized data management. They can be declared, defined, and initialized in various ways, and are useful for representing complex data like students or books. However, C structures have limitations such as higher memory consumption and lack of data hiding, while unions allow for storing different data types in the same memory location, with only one member being active at a time.

Uploaded by

Prajukta Das
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/ 11

C Structures:

The structure in C is a user-defined data type that can be used to group items of possibly different types into a
single type. The struct keyword is used to define the structure in the C programming language. The items in the
structure are called its member and they can be of any valid data type.

Why use structure?


In C, there are cases where we need to store multiple attributes of an entity. It is not necessary that an entity has all
the information of one type only. It can have different attributes of different data types. For example, an
entity Student may have its name (string), roll number (int), marks (float). To store such type of information
regarding an entity student
o Construct individual arrays for storing names, roll numbers, and marks:The above process may fulfill
our requirement but the program is very complex, and the complexity increase with the amount of the
input.
o Use a special data structure to store the collection of different data types: C provides you with an
additional and simpler approach where you can use a special data structure, i.e., structure, in which, you can
group all the information of different data type regarding an entity.
C Structure Declaration:
we specify its member variables along with their datatype. ‘struct’ keyword to declare the structure in C using the
following syntax:

Syntax:
structstructure_name {
data_type member_name1;
data_type member_name1;
....
....
};
The above syntax is also called a structure template or structure prototype and no memory is allocated to the
structure in the declaration.

C Structure Definition:
Structure Variable Declaration with Structure Template
structstructure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;

Access Structure Members


We can access structure members by using the ( . ) dot operator.
Syntax
structure_name.member1;
strcuture_name.member2;
In the case where we have a pointer to the structure, we can also use the arrow operator to access the members.

Initialize Structure Members:


Structure members cannot be initialized with the declaration. For example, the following C program fails in the
compilation.
struct Point{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here

};
The reason for the above error is simple. When a datatype is declared, no memory is allocated for it. Memory is
allocated only when variables are created.

We can initialize structure members in 3 ways which are as follows:

1. Using Assignment Operator.


2. Using Initializer List.
3. Using Designated Initializer List.

1. Initialization using Assignment Operator


structstructure_name str;
str.member1 = value1;
str.member2 = value2;
str.member3 = value3;

2. Initialization using Initializer List


structstructure_name str = { value1, value2, value3 };
In this type of initialization, the values are assigned in sequential order as they are declared in the structure
template.

3. Initialization using Designated Initializer List


Designated Initialization allows structure members to be initialized in any order. This feature has been added in
the C99 standard.
structstructure_name str = { .member1 = value1, .member2 = value2, .member3 = value3 };

Example of Structure in C:
#include <stdio.h>
#include<string.h>
structBooks
{

chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;
};

intmain()
{

structBooksBook1; /*DeclareBook1oftypeBook*/
structBooksBook2; /*DeclareBook2 oftypeBook */

/*book 1specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");

strcpy( Book1.subject, "C Programming Tutorial");


Book1.book_id = 6495407;

/*book2 specification*/
strcpy( Book2.title, "Telecom Billing");

strcpy( Book2.author, "Zara Ali");

strcpy(Book2.subject, "Telecom Billing Tutorial");

Book2.book_id = 6495700;

/*printBook1info*/
printf( "Book 1 title : %s\n", Book1.title);

printf( "Book 1 author : %s\n", Book1.author);


printf( "Book 1 subject : %s\n", Book1.subject);

printf( "Book 1 book_id : %d\n", Book1.book_id);

/*printBook2info*/
printf( "Book 2 title : %s\n", Book2.title);

printf( "Book 2 author : %s\n", Book2.author);

printf( "Book 2 subject : %s\n", Book2.subject);

printf( "Book 2 book_id : %d\n", Book2.book_id);

return0;

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:

Book 1 title:CProgramming
Book 1 author:NuhaAli
Book 1 subject :CProgrammingTutorial
Book 1 book_id:6495407
Book 2 title:TelecomBilling
Book 2 author:ZaraAli
Book 2 subject:TelecomBillingTutorial
Book 2 book_id:6495700

StructuresasFunctionArguments:
Youcanpassastructureasafunctionargumentinverysimilarwayasyoupassanyothervariable
orpointer.Youwouldaccessstructurevariablesinthesimilarwayasyouhaveaccessedinthe above example:

#include <stdio.h>
#include<string.h>
structBooks
{
chartitle[50];
charauthor[50];
charsubject[100];
int book_id;
};
/*functiondeclaration*/
void printBook(structBooksbook);
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
structBooksBook2; /*DeclareBook2 oftypeBook */

/*book 1specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;

/*book2 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 );
return0;
}

voidprintBook(structBooksbook)

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);

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Book title : C Programming Book
author : Nuha Ali
Booksubject:C Programming Tutorial Book
book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Booksubject:Telecom Billing Tutorial Book
book_id : 6495700

Array of Structures in C:

An array of structures in C can be defined as the collection of multiple structures variables where each variable
contains information about different entities. The array of structures in C are used to store information about
multiple entities of different data types. The array of structures is also known as the collection of structures.

Example:
1. #include<stdio.h>
2. #include <string.h>
3. struct student{
4. int rollno;
5. char name[10];
6. };
7. int main(){
8. int i;
9. struct student st[5];
10. printf("Enter Records of 5 students");
11. for(i=0;i<5;i++){
12. printf("\nEnter Rollno:");
13. scanf("%d",&st[i].rollno);
14. printf("\nEnter Name:");
15. scanf("%s",&st[i].name);
16. }
17. printf("\nStudent Information List:");
18. for(i=0;i<5;i++){
19. printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
20. }
21. return 0;
22. }

Output:

Enter Records of 5 students


Enter Rollno:1
Enter Name:Sonu
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz

Structure Pointer in C:
We can define a pointer that points to the structure like any other variable. Such pointers are generally
called Structure Pointers. We can access the members of the structure pointed by the structure pointer using
the ( > ) arrow operator.

Example of Structure Pointer:

#include <stdio.h>

// structure declaration
structPoint {
intx, y;
};
intmain()
{
structPoint str = { 1, 2 };
// p2 is a pointer to structure p1
structPoint* ptr = &str;
// Accessing structure members using structure pointer
printf("%d %d", ptr->x, ptr->y);

return0;
}

Output
1 2
Bit Fields:
Bit Fields are used to specify the length of the structure members in bits. When we know the maximum length of
the member, we can use bit fields to specify the size and reduce memory consumption.

Syntax of Bit Fields:


struct structure_name{
data_typemember_name: width_of_bit-field;
};

Example of Bit Fields:

#include <stdio.h>

// declaring structure for reference


structstr1 {
inta;
charc;
};

// structure with bit fields


structstr2 {
inta : 24; // size of 'a' is 3 bytes = 24 bits
charc;
};

// driver code
intmain()
{
printf("Size of Str1: %d\nSize of Str2: %d",
sizeof(structstr1), sizeof(structstr2));
return0;
}

Output
Size of Str1: 8

Size of Str2: 4
As we can see, the size of the structure is reduced when using the bit field to define the max size of the member
‘a’.

Uses of Structure in C:
C structures are used for the following:

1. The structure can be used to define the custom data types that can be used to create some complex
data types such as dates, time, complex numbers, etc. which are not present in the language.
2. It can also be used in data organization where a large amount of data can be stored in different fields.
3. Structures are used to create data structures such as trees, linked lists, etc.
4. They can also be used for returning multiple values from a function.

Limitations of C Structures:
In C language, structures provide a method for packing together data of different types. A Structure is a helpful
tool to handle a group of logically related data items. However, C structures also have some limitations.

 Higher Memory Consumption: It is due to structure padding.


 No Data Hiding: C Structures do not permit data hiding. Structure members can be accessed by any
function, anywhere in the scope of the structure.
 Functions inside Structure: C structures do not permit functions inside the structure so we cannot
provide the associated functions.
 Static Members: C Structure cannot have static members inside its body.
 Construction creation in Structure: Structures in C cannot have a constructor inside Structures.

C – 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.

C Union Declaration:
No memory is allocated to the union in the declaration.
unionunion_name {
datatype member1;
datatype member2;
...
};
Keep in mind that we have to always end the union declaration with a semi-colon.

Different Ways to Define a Union Variable:


We need to define a variable of the union type to start using union members. There are two methods using
which we can define a union variable.
1. With Union Declaration
2. After Union Declaration
1. Defining Union Variable with Declaration
unionunion_name {
datatype member1;
datatype member2;
...
} var1, var2, ...;
2. Defining Union Variable after Declaration
unionunion_name var1, var2, var3...;
where union_name is the name of an already declared union.

Access Union Members:


We can access the members of a union by using the ( . ) dot operator just like structures.
var1.member1;
where var1 is the union variable and member1 is the member of the union.

Initialization of Union in C:
The initialization of a union is the initialization of its members by simply assigning the value to it.
var1.member1 = value;
One important thing to note here is that only one member can contain some value at a given instance of
time.

Example of Union:
#include <stdio.h>
// union template or declaration
unionun {
intmember1;
charmember2;
floatmember3;
};
intmain()
{ // defining a union variable
unionun var1;
// initializing the union member
var1.member1 = 15;
printf("The value stored in member1 = %d",var1.member1);
return0;
}

Output:
The value stored in member1 = 15

Size of Union:
The size of the union will always be equal to the size of the largest member of the array. All the less -sized
elements can store the data in the same space without any overflow.

// C Program to find the size of the union


#include <stdio.h>
// declaring multiple unions
uniontest1 {
intx;
inty;
} Test1;

uniontest2 {
intx;
chary;
} Test2;

uniontest3 {
intarr[10];
chary;
} Test3;

// driver code
intmain()
{
// finding size using sizeof() operator
intsize1 = sizeof(Test1);
intsize2 = sizeof(Test2);
intsize3 = sizeof(Test3);
printf("Sizeof test1: %d\n", size1);
printf("Sizeof test2: %d\n", size2);
printf("Sizeof test3: %d", size3);
return0;
}

Output
Sizeof test1: 4
Sizeof test2: 4
Sizeof test3: 40

Difference between C Structure and C Union:


Point of
Structure Union
Difference

Memory
Allocates memory for all its members. Allocates memory only for the largest member.
Allocation

Total Size Sum of sizes of all members. Size of the largest member.

Data Can store values for all members


Can store value for only one member at a time.
Storage simultaneously.

When you want to group different data When you want to save memory and only need one data
Use Case
types and access all of them at once. type at a time.

To define a structure, we utilise the struct


To define a union, we use the union keyword
statement.
union example {
struct example {
Example int a;
int a;
float b;
float b;
}
}

Accessing All members can be accessed at any


Only one member can be accessed or retrieved at a time
Members time.

Modification Modifying a member doesn’t affect other


Modifying one member may overwrite other members.
Impact members.

Enum in C:
The enum in C is also known as the enumerated type. It is a user-defined data type that consists of integer values,
and it provides meaningful names to these values. The use of enum in C makes the program easy to understand
and maintain. The enum is defined by using the enum keyword.

The following is the way to define the enum in C:


enum flag{integer_const1, integer_const2,.....integter_constN};
In the above declaration, we define the enum named as flag containing 'N' integer constants. The default value of
integer_const1 is 0, integer_const2 is 1, and so on. We can also change the default value of the integer constants at
the time of the declaration.
enum fruits{mango, apple, strawberry, papaya};

The default value of mango is 0, apple is 1, strawberry is 2, and papaya is 3. If we want to change these
default values, then we can do as given below:

enum fruits{
mango=2,
apple=1,
strawberry=5,
papaya=7,
};

Enumerated type declaration:


enum status{false,true} s; // we create the enum of type status and we create the variable ‘s’ of status type

In this case, the default value of false will be equal to 0, and the value of true will be equal to 1.

Example of Enum:

1. #include <stdio.h>
2. enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
3. int main()
4. {
5. enum weekdays w; // variable declaration of weekdays type
6. w=Monday; // assigning value of Monday to w.
7. printf("The value of w is %d",w);
8. return 0;
9. }
Output:

The value of w is 2 // If we do not provide any value to the enum names, then the compiler will
//automatically assign the default values to the enum names starting from 0.

In the above code, we create an enum type named as weekdays, and it contains the name of all the seven days. We
have assigned 1 value to the Sunday, and all other names will be given a value as the previous value plus one.

The enum names available in an enum type can have the same value. Let's look at the example.

1. #include <stdio.h>
2.
3. int main(void) {
4. enum fruits{mango = 1, strawberry=0, apple=1};
5. printf("The value of mango is %d", mango);
6. printf("\nThe value of apple is %d", apple);
7. return 0;
8. }

Output:
The value of mango is 1
The value of apple is 1

All enum constants must be unique in their scope. For example, the following program fails in
compilation.
enumstate {working, failed};
enumresult {failed, passed};

intmain() { return0; }
Output:
Compile Error: 'failed' has a previous declaration as 'state failed'

Let's see how we can use an enum in a switch case statement:


1. #include <stdio.h>
2. enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday};
3. int main()
4. {
5. enum days d;
6. d=monday;
7. switch(d)
8. {
9. case sunday:
10. printf("Today is sunday");
11. break;
12. case monday:
13. printf("Today is monday");
14. break;
15. case tuesday:
16. printf("Today is tuesday");
17. break;
18. case wednesday:
19. printf("Today is wednesday");
20. break;
21. case thursday:
22. printf("Today is thursday");
23. break;
24. case friday:
25. printf("Today is friday");
26. break;
27. case saturday:
28. printf("Today is saturday");
29. break;
30. }
31. return 0;
32. }

Output:
Today is Monday

You might also like