Skip to main content

C programming- structure

Structures and unions are fundamental components in the C programming language that allow for the grouping of different data types. Here’s a detailed explanation of their definitions, declarations, initializations, and differences.

4.3.1 Structure: Definition, Declaration, Initialization, and Size

Definition

A structure in C is a user-defined data type that allows the combination of data items of different kinds. Structures are used to represent a record. For example, a structure can hold information about a student, including their name, age, and grade.

Declaration

To declare a structure, the struct keyword is used followed by the structure name and its members enclosed in braces. For example:
c
struct Student { char name[50]; int age; float grade; };

Initialization

Structures can be initialized at the time of declaration using an initializer list. For example:
c
struct Student student1 = {"John Doe", 20, 3.5};

Size

The size of a structure is determined by the total size of its members plus any padding added by the compiler for alignment purposes. The size can be obtained using the sizeof operator:
c
printf("Size of Student: %lu\n", sizeof(struct Student));

4.3.2 Accessing Members of a Structure

Members of a structure can be accessed using the dot operator (.) for structure variables and the arrow operator (->) for pointers to structures. For example:
c
struct Student student1; student1.age = 20; // Using dot operator struct Student *ptr = &student1; ptr->grade = 3.5; // Using arrow operator

4.3.3 Array of Structures

An array of structures allows multiple records of the same type to be stored. For example:
c
struct Student students[100]; // Array of 100 students students[0].age = 20; // Accessing the first student's age

4.3.4 Union: Definition and Declaration

Definition

A union is similar to a structure in that it is a user-defined data type that can hold different types of data. However, a union can only store one of its members at any given time, as all members share the same memory location.

Declaration

A union is declared using the union keyword. For example:
c
union Data { int intValue; float floatValue; char charValue; 

};

Differences between structure and union are as follows:


Here’s a comparison of structures and unions in C programming presented in a table format:
FeatureStructureUnion
Memory AllocationAllocates separate memory for each member.Allocates memory equal to the size of the largest member.
Data StorageAll members can hold values simultaneously.Only one member can hold a value at any time.
Keyword UsedDefined using the struct keyword.Defined using the union keyword.
InitializationCan be initialized with values for all members.Can only be initialized for one member at a time.
Accessing MembersAccessed using the dot operator (.) or arrow operator (->).Accessed in the same way, but only the last assigned member holds valid data.
Use CaseSuitable for representing complex data types with multiple attributes.More efficient for scenarios where only one of several types is needed at a time.
Size CalculationSize can be larger due to padding and all member sizes.Size is determined solely by the largest member.
Data IntegrityMaintains integrity of all member data.Risk of data corruption as only one member can be valid at a time.
ComplexityGenerally more complex due to the ability to hold multiple values.Simpler in terms of memory management but can lead to confusion.
PerformanceMay incur slight overhead due to larger memory footprint.Can be more performance-efficient when only one member is needed.

Differences between array and structure
FeatureArrayStructure
Memory AllocationElements are stored in contiguous memory locations.Elements may or may not be stored in contiguous memory locations.
Data TypesCan only store elements of the same data type.Can store elements of different data types.
SizeSize is fixed and determined by the number of elements multiplied by the size of each element.Size is not fixed as each element can be of different type and size.
Accessing ElementsElements are accessed using an index with square brackets [].Elements are accessed using the dot operator ..
PointerThe array name is a pointer to the first element.The structure name is not a pointer.
InstantiationCreating objects or instances is not possible.Creating objects or instances is possible.
Bit FieldBit fields are not allowed.Bit fields are allowed.
KeywordNo specific keyword is used for declaration.The struct keyword is used for declaration.
Data TypeA non-primitive data type.A user-defined data type.
Traversal and SearchingTraversal and searching are easy and fast.Traversal and searching are complex and slow.

 

Comments

Popular posts from this blog

Software Process Model(SPM)

  Explain spiral development model with advantages and disadvantages The Spiral Development Model is a risk-driven software development approach that combines iterative and waterfall models. It involves repeated cycles (or spirals) to incrementally refine the software project. Each spiral consists of four major phases: Planning , Risk Analysis , Engineering , and Evaluation .                                                           Fig: Spiral Software development model Phases in the Spiral Model: Planning : Requirements are gathered and objectives are set for the project. Risk Analysis : Risks are identified, analyzed, and mitigation strategies are developed. Develop/Engineering : The actual development and testing of the product take place. Evaluation : Stakeholders/users review the progress and provide feedback, inf...

Solution of NEB model quetions

 solution to model questions are : 

DBMS-SQL

SQL DDL and DML Examples Examples of DDL (Data Definition Language) and DML (Data Manipulation Language) commands in SQL. DDL (Data Definition Language) Examples: 1. Create a new database: CREATE DATABASE SchoolDB;  2. Create a table: CREATE TABLE Students ( StudentID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50), Age INT );  3. Alter a table to add a new column: ALTER TABLE Students ADD Email VARCHAR(100);  4. Drop a table: DROP TABLE Students;  5. Rename a table: ALTER TABLE OldTableName RENAME TO NewTableName;  DML (Data Manipulation Language) Examples: 1. Insert data into a table:  INSERT INTO Students (StudentID, FirstName, LastName, Age) VALUES (1, 'John', 'Doe', 20);  2. Update data in a table: UPDATE Students SET Age = 21 WHERE StudentID = 1;  3. Delete data from a table: DELETE FROM Students WHERE StudentID = 1;  4. Select data from a table: SELECT * FROM Students;  5. Select data with conditions: SELECT FirstName...