0% found this document useful (0 votes)
22 views17 pages

Unit 4 QB

Uploaded by

kuttysangeeth33
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)
22 views17 pages

Unit 4 QB

Uploaded by

kuttysangeeth33
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/ 17

Unit -4 Structure and union

Question bank

1. Define a structure in C and explain its purpose.


A structure is a user-defined data type that allows the grouping of variables of different types under a
single name. Each variable within a structure is called a member or field. A structure is particularly
useful when you want to represent a complex data item that consists of multiple attributes, such as a
record in a database, or information about an object.

2. Write the general syntax for declaring a structure in C.

struct structure_name {
data_type member1;
data_type member2;
...
};
3. Provide an example of a structure for storing details of a student.
struct Student {
char name[50];
int roll_no;
float marks;
};

4. Explain how to initialize a structure variable with an example.


Initialization at the time of Declaration:
initialize the members of a structure directly at the time of declaration by providing values for each
member in the order in which they are declared in the structure
struct structure_name variable_name = {value1, value2, value3, ...};
Example:
struct Student {
char name[50];
int roll_no;
float marks;
};
struct Student student1 = {"John Doe", 101, 85.5};

5. What is the difference between dot operator (.) and arrow operator (->) for accessing structure
members?
Dot Operator (.):
The dot operator is used to access members of a structure using a structure variable (i.e., an instance
of a structure).
Synatx: structure_variable.member
struct Student {
char name[50];
int roll_no;
};
int main() {
struct Student student1 = {"John", 101};
printf("Name: %s\n", student1.name);
printf("Roll No: %d\n", student1.roll_no);
}

Arrow Operator (->):


The arrow operator is used to access members of a structure using a pointer to a structure.
Syntax:structure_pointer->member

struct Student student1 = {"John", 101};


struct Student *ptr = &student1;
printf("Name: %s\n", ptr->name);
printf("Roll No: %d\n", ptr->roll_no);

6. Write a C code snippet to declare and use an array of structures.


struct Student {
char name[50];
int roll_no;
float marks;
};

struct Student students[3] = {


{"John", 101, 85.5},
{"Alice", 102, 90.0},
{"Bob", 103, 88.5}
};
7. Explain the concept of a structure pointer with an example.
A structure pointer is a pointer that points to a structure. It is used when you need to access the
members of a structure dynamically (i.e., through a pointer) rather than directly accessing the structure
variable. To access the members of a structure via a pointer, the arrow operator (->) is used.
struct Student student1 = {"John", 101};
struct Student *ptr = &student1;
printf("Name: %s\n", ptr->name);
printf("Roll No: %d\n", ptr->roll_no);
8. Define a self-referenced structure and write an example for a singly linked list.
A self-referenced structure is a structure that contains a pointer to itself. This type of structure is
commonly used to represent linked data structures like linked lists

A singly linked list consists of nodes, where each node contains:

1. Data (could be an integer, string, etc.)


2. A pointer to the next node in the list.

Each node of the list is represented by a structure that has a self-referenced pointer to the next node

struct Node {
int data; // Data field to store the value
struct Node* next; // Pointer to the next node (self-referenced structure)
};
9. Differentiate between single-linked and multi-linked with respect to structures.

Feature Single-Linked List Multi-Linked List

Number of Pointers One pointer (next) to link Multiple pointers (e.g., next
nodes in a single direction and prev) or more, enabling
complex relationships

Traversal Unidirectional (can only be Can be bidirectional (e.g., in


traversed from head to tail) doubly linked lists) or even
multidirectional (in multi-
dimensional lists)

Complexity Simpler structure and traversal More complex structure and


traversal due to multiple
pointers

Memory Usage Uses less memory per node (1 Uses more memory per node
pointer) (multiple pointers)

Types of Links Links nodes in a single chain Links nodes across multiple
dimensions (e.g., doubly linked
list or multidimensional list)

10. Explain nested structures (embedded structures) and provide a suitable example.
A nested structure (also known as an embedded structure) is a structure that contains another
structure as one of its members.
Syntax:
struct OuterStructure {
struct InnerStructure inner; // Embedding another structure inside
// other members...
};

Example:
struct Address {
char street[100];
char city[50];
int postal_code;
};

struct Student {
char name[50];
int roll_no;
struct Address addr; // Nested structure
};

11. How is memory allocated for structures in C?


memory for structures is allocated based on the size of their members, with padding added to ensure
proper alignment
Example:
struct Example {
char c; // 1 byte
int i; // 4 bytes
};
The Example structure contains a char (1 byte) and an int (4 bytes).
The total size of the structure is typically 8 bytes due to padding (1 byte for char + 3 bytes of
padding + 4 bytes for int).
Padding is applied to characters (and other data types) in structures in C to ensure proper memory
alignment.

12. List two applications of structures in real-world programming scenarios.

Handling Employee Information


In a business application, a structure can be used to represent employee details, such as name, ID,
department, and salary.

struct Employee {

char name[100];

int emp_id;

char department[50];

float salary;

};

Handling Student Grades

In educational applications, structures can represent a student's grades across different subjects. It
makes it easier to track and manipulate a student's performance.

struct Grade {

char subject[50];

float grade;

};

13. Define a union and explain its purpose in memory management.


A union in C is a special data structure that allows multiple variables (members) to share the same
memory location.
Memory Size: The size of a union is equal to the size of its largest member, since all members
share the same memory.
Use Case: Unions are particularly useful when it is required to store different types of data but do
not need to store them simultaneously. For example, in applications like network protocols or
embedded systems, where different data formats are used at different times.

14. Write the syntax for declaring and initializing a union in C.


union UnionName {
dataType member1;
dataType member2;
// more members
};
15. Provide an example where a union is used to represent a variant data type (e.g., int, float, char).
union Data
{
int i;
char c;
}u1;
int main()
{
u1.c='a';
printf("%d",u1.i);
return 0;
}
16. Explain the memory allocation in unions and compare it with structures.
Aspect Union Structure

Memory Allocation All members share the same memory Each member gets its own
location. memory location.

Size Size of the union is the size of the Size of the structure is the sum of
largest member. all member sizes, plus padding.

Usage Suitable for situations where only one Suitable for cases where all
member is used at a time. members need to be accessed
simultaneously.

Example Size union Data { int i; float f; char c; } → struct Data { int i; float f; char c; }
4 bytes. → 12 bytes (or 9 bytes with no
padding).

Memory Efficiency More memory-efficient because only Less memory-efficient because all
one member is used at a time. members are stored at once.

17. How would you access a member of a union using a pointer? Provide an example.

Steps to Access Union Members via Pointer:

1. Declare a pointer to the union.


2. Assign the address of the union variable to the pointer.
3. Use the arrow operator (->) to access the members of the union.
union SensorData {
int temp; // Integer data (e.g., temperature)
float hum; // Float data (e.g., humidity)
char status; // Char data (e.g., status)
}sensor;

union SensorData *ptr = &sensor;


ptr->temp = 65.5;
printf("Temperature: %.2f\n", ptr->temp);

18. State two key differences between a structure and a union.

Aspect Union Structure

Memory Allocation All members share the same memory Each member gets its own
location. memory location.

Size Size of the union is the size of the Size of the structure is the sum of
largest member. all member sizes, plus padding.

19. Analyze the following code snippet and identify any errors:

struct Example {
int a;
float b;
} ex;
ex.a = 10;
printf("%d", b);

Answer:
a is the member of the structure. To access it, ex.a should be used in the printf statement.

20. Find the memory required for the following structure:

struct Sample {
int id;
char name[20];
float salary;
};
In this structure, the total size without considering padding would be:

4 bytes (int) + 20 bytes (char array) + 4 bytes (float) = 28 bytes.

21. Write short notes on storage classes in C and their use in variable declarations.
storage classes determine the scope, lifetime, visibility, and memory location of variables. The four
primary storage classes are:
 Auto
 Register
 Static
 Extern

22. Explain the difference between auto and register storage classes.
Aspect auto Storage Class register Storage Class

Memory Location Stored in the stack memory of Stored in the CPU register (if
the program. available); otherwise, stored in
stack.

Default Behavior Default storage class for local Must be explicitly specified
variables. using the register keyword.

Access Speed Slower compared to register as Faster, as CPU registers are


variables are in stack memory. directly accessed.

Scope Limited to the block or Same as auto: block or function


function in which it is declared. scope.

Lifetime Exists until the block in which Same as auto: exists until the
it is declared exits. block exits.

Initialization Contains garbage value if not Contains garbage value if not


explicitly initialized. explicitly initialized.

Addressing Can take the address using the Cannot take the address using
& operator. & (registers don't have memory
addresses).

Variables needing frequent


Use Case General-purpose local variables. access, e.g., loop counters or
frequently used variables.
23. Provide an example demonstrating the use of the static storage class in maintaining variable state.
#include <stdio.h>

// Function to demonstrate the use of static


void counterFunction() {
static int count = 0; // Static variable retains its value
count++;
printf("Count: %d\n", count);
}

int main() {
// Call the function multiple times
counterFunction(); // First call
counterFunction(); // Second call
counterFunction(); // Third call

return 0;
}
24. What is the purpose of the extern keyword in C? Write a code snippet to illustrate its usage.
The extern keyword in C is used to declare a global variable or function that is defined in another file
or scope. It allows variables or functions to be shared across multiple files in a program.

File1.c:
int a=10;
void message()
{
printf("Hello from File1");
}
File2.c:
#include <stdio.h>
extern int a; //a is in external file
extern void message();
int main()
{
printf("%d",a);
message();
return 0;
}

Write a program to declare and initialize a structure to store employee details (ID, Name, Salary).
#include <stdio.h>

// Define the structure to store employee details


struct Employee {
int id; // Employee ID
char name[50]; // Employee Name
float salary; // Employee Salary
};

int main() {
// Declare and initialize an Employee structure
struct Employee emp1 = {101, "John Doe", 50000.50};

// Display the employee details


printf("Employee Details:\n");
printf("ID: %d\n", emp1.id);
printf("Name: %s\n", emp1.name);
printf("Salary: %.2f\n", emp1.salary);

return 0;
}
Justify the use of structures in real-world applications by providing at least two practical examples.

Structures in C allow developers to group related data types into a single unit, making it easier to
manage and organize complex data. Here are two practical examples demonstrating their utility:

1. Employee Management System

In a real-world scenario, an organization needs to manage employee records, including details such as
employee ID, name, department, and salary. A structure simplifies the representation of each employee
as a single unit.

struct Employee {

int id;

char name[50];

char department[20];

float salary;

};

Purpose: Structures provide a logical grouping of employee attributes, making the data easy to
process, store, and transfer.

Use: Managing payroll systems, HR databases, and performance tracking systems.

Sensor Data in Embedded Systems

In embedded systems, sensor data from devices like temperature sensors, humidity sensors, and
pressure sensors are collected and processed. Structures can represent multiple data points.

struct SensorData {

int sensorID;

float temperature;

float humidity;
};

Purpose: Groups related sensor information for easy processing and monitoring.

Use: Real-time monitoring in IoT (Internet of Things) systems or industrial automation.

Medical Records

Healthcare systems store patient data, such as ID, name, medical history, and test results. Structures
help organize and access this data.

struct Patient {

int patientID;

char name[50];

char medicalHistory[200];

float testResults[5];

};

Purpose: Organizes patient details for diagnostics and treatment.

Use: Electronic health records (EHR) systems, hospital management software.

2. (a) Explain the concept of nested structures with an example to represent a student’s marks
and personal details. (b) Analyze the memory allocation for the above structure and calculate the
total memory consumed. (8+5)

A nested structure (also known as an embedded structure) is a structure that contains another
structure as one of its members.
Syntax:
struct OuterStructure {
struct InnerStructure inner; // Embedding another structure inside
// other members...
};
#include <stdio.h>

// Structure for marks


struct Marks {
float math;
float physics;
float chemistry;
};

// Structure for personal details, embedding the Marks structure


struct Student {
int rollNumber;
char name[50];
struct Marks scores; // Nested structure
};

int main() {
// Declare and initialize a student structure
struct Student student1 = {101, "John Doe", {85.5, 90.0, 78.5}};

// Display the student's details and marks


printf("Student Details:\n");
printf("Roll Number: %d\n", student1.rollNumber);
printf("Name: %s\n", student1.name);
printf("Marks:\n");
printf(" Math: %.2f\n", student1.scores.math);
printf(" Physics: %.2f\n", student1.scores.physics);
printf(" Chemistry: %.2f\n", student1.scores.chemistry);

return 0;
}

Memory Allocation for the Structure

1. Marks Structure:
o float math: 4 bytes
o float physics: 4 bytes
o float chemistry: 4 bytes
o Total for Marks: 12 bytes
2. Student Structure:
o int rollNumber: 4 bytes
o char name[50]: 50 bytes
o struct Marks scores: 12 bytes (embedded structure)
o Total for Student:
Without padding: 4+50+12=664 + 50 + 12 = 664+50+12=66 bytes

3. (a) Compare and contrast the memory allocation of structures and unions with a
diagrammatic explanation.
Structure Union

In structure each member get separate space in In union, the total memory space allocated is equal
memory. Take below example. to the member with largest size. All other
members share the same memory space. This is
the biggest difference between structure and
union.
struct student

{
union student
int rollno;
{
char gender;
int rollno;
float marks;
char gender;
}s1; float marks;

}s1;

The total memory required to store a structure


variable is equal to the sum of size of all the
members. In above case 7 bytes (2+1+4) will In above example variable marks is of float type
be required to store structure variable s1. and have largest size (4 bytes). So the total
memory required to store union variable s1 is
4 bytes.

We can access any member in any sequence. We can access only that variable whose value is
recently stored.

s1.rollno = 20;
s1.rollno = 20;
s1.marks = 90.0;
s1.marks = 90.0;
printf(“%d”,s1.rollno);
printf(“%d”,s1.rollno);

The above code will work fine but will show


erroneous output in the case of union. The above code will show erroneous output. The
value of rollno is lost as most recently we have
stored value in marks. This is because all
the members share same memory space.

All the members can be initialized while declaring Only first member can be initialized while
the variable of structure. declaring the variable of union. In above example
we can initialize only variable rollno at the time
of declaration of variable.
Write a program to demonstrate the use of unions in handling data of multiple types (e.g., integer,
float, and string).

#include <stdio.h>
#include <string.h>

// Define a union to store multiple types of data


union Data {
int intVal;
float floatVal;
char strVal[20];
};

int main() {
union Data data;
// Assign and display integer value
data.intVal = 25;
printf("After assigning intVal:\n");
printf("intVal: %d\n", data.intVal);

// Assign and display float value


data.floatVal = 3.14;
printf("\nAfter assigning floatVal:\n");
printf("floatVal: %.2f\n", data.floatVal);

// Assign and display string value


strcpy(data.strVal, "Hello, World!");
printf("\nAfter assigning strVal:\n");
printf("strVal: %s\n", data.strVal);

// Observe overwriting effect


printf("\nAccessing other members after assigning strVal:\n");
printf("intVal: %d\n", data.intVal); // Overwritten value
printf("floatVal: %.2f\n", data.floatVal); // Overwritten value

return 0;
}

You might also like