0% found this document useful (0 votes)
14 views16 pages

Understanding Structures in C Programming

Uploaded by

Anandakrishnan
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)
14 views16 pages

Understanding Structures in C Programming

Uploaded by

Anandakrishnan
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

MODULE IV

STRUCTURE

● A structure is a keyword that creates user defined data types in C.


● A structure creates a data type that can be used to group items of different types into a
single type.
● ie, Unlike an array, a structure can contain many different data types (int, float, char,
etc.).

Definition:-
● Structure in c is a user-defined data type that enables us to store the collection of
different data types.
● Each element of a structure is called a member.
● ‘struct’ keyword is used to create a structure.

Syntax:-
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memberN;
};

Example:-
struct employee
{ int id;
char name[20];
float salary;
};
Declaring structure variable
There are two ways to declare structure variable:
1. By struct keyword within main() function
struct employee
{ int id;
char name[50];
float salary;
};
Give below code inside the main() function-
struct employee e1, e2;

2. By declaring a variable at the time of defining the structure.

struct employee
{ int id;
char name[50];
float salary;
}e1,e2;

Accessing members of the structure

By using . (member or dot operator)

Eg. [Link]

Example:-

#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
[Link]=101;
strcpy([Link], "Arun");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", [Link]);
printf( "employee 1 name : %s\n", [Link]);
return 0;
}

Output:

employee 1 id : 101
employee 1 name : Arun

Array of Structures

● An array of structures in C can be defined as the collection of multiple structure


variables where each variable contains information about different entities.
● The array of structures is also known as the collection of structures.

Example of an array of structures that stores information of 5 students and prints it:-
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}

Output:

Enter Records of 5 students


Enter Rollno:1
Enter Name:Arun
Enter Rollno:2
Enter Name:Ram
Enter Rollno:3
Enter Name:Vijay
Enter Rollno:4
Enter Name:John
Enter Rollno:5
Enter Name:Sam

Student Information List:


Rollno:1, Name:Arun
Rollno:2, Name:Ram
Rollno:3, Name:Vijay
Rollno:4, Name:John
Rollno:5, Name:Sam
Structure and Pointer

● A structure pointer is defined as the pointer which points to the address of the
memory block that stores a structure.
● The declaration of a structure pointer is similar to the declaration of the structure
variable.
● So, we can declare the structure pointer and variable inside and outside of the main()
function.
● To declare a pointer variable in C, we use the asterisk (*) symbol before the variable's
name.
Syntax:
struct structure_name *ptr;

Initialization of the Structure Pointer:-


ptr = &structure_variable;

Example 1:
#include <stdio.h>
struct person
{
int age;
float weight;
};

int main()
{
struct person *personPtr, person1;
personPtr = &person1;

printf("Enter age: ");


scanf("%d", &personPtr->age);

printf("Enter weight: ");


scanf("%f", &personPtr->weight);

printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);

return 0;
}

Example 2:
// C program to demonstrate structure pointer
#include <stdio.h>

struct point {
int value;
};

int main()
{

struct point s;

// Initialization of the structure pointer


struct point* ptr = &s;

return 0;
}

Example 3:
// C Program to demonstrate Structure pointer
#include <stdio.h>
#include <string.h>

struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};

int main()
{

struct Student s1;


struct Student* ptr = &s1;

s1.roll_no = 2;
strcpy([Link], "Arun");
strcpy([Link], "CHE");
[Link] = 2022;

printf("Roll Number: %d\n", (*ptr).roll_no);


printf("Name: %s\n", (*ptr).name);
printf("Branch: %s\n", (*ptr).branch);
printf("Batch: %d", (*ptr).batch);
return 0;
}

Structure and Function

passing structures to a function:-

#include <stdio.h>
struct student {
char name[50];
int age;
};

// function prototype
void display(struct student s);

int main() {
struct student s1;

printf("Enter name: ");

// read string input from the user until \n is entered


// \n is discarded
scanf("%s", [Link]);

printf("Enter age: ");


scanf("%d", &[Link]);

display(s1); // passing struct as an argument

return 0;
}

void display(struct student s) {


printf("\nDisplaying information\n");
printf("Name: %s", [Link]);
printf("\nAge: %d", [Link]);
}

Output:-

Enter name: Abin


Enter age: 21
Displaying information
Name: Abin
Age: 21

Program to return struct from a function:-

#include <stdio.h>
struct student
{
char name[50];
int age;
};

// function prototype
struct student getInformation();

int main()
{
struct student s;

s = getInformation();

printf("\nDisplaying information\n");
printf("Name: %s", [Link]);
printf("\nRoll: %d", [Link]);

return 0;
}
struct student getInformation()
{
struct student s1;

printf("Enter name: ");


scanf("%s", [Link]);

printf("Enter age: ");


scanf("%d", &[Link]);

return s1;
}

Passing struct by reference:-


● During pass by reference, the memory addresses of struct variables are passed to the
function.

#include <stdio.h>
struct Complex
{
float real;
float imag;
} com;

void addNumbers(com c1, com c2, com *result);

int main()
{
com c1, c2, result;

printf("For first number,\n");


printf("Enter real part: ");
scanf("%f", &[Link]);
printf("Enter imaginary part: ");
scanf("%f", &[Link]);

printf("For second number, \n");


printf("Enter real part: ");
scanf("%f", &[Link]);
printf("Enter imaginary part: ");
scanf("%f", &[Link]);

addNumbers(c1, c2, &result);


printf("\[Link] = %.1f\n", [Link]);
printf("[Link] = %.1f", [Link]);

return 0;
}
void addNumbers(com c1, com c2, com *result)
{
result->real = [Link] + [Link];
result->imag = [Link] + [Link];
}

Union in C

● A union is a special data type available in C that allows to store different data types in
the same memory location.
● Unions provide an efficient way of using the same memory location for
multiple-purpose.

Syntax:

union [union name]


{
member definition;
member definition;
...
member definition;
};

(OR)

union [union name]


{
member definition;
member definition;
...
member definition;
}union variable declaration;

Example:

union abc
{
int a;
char b;
}var;
int main()
{
var.a = 66;
printf("\n a = %d", var.a);
printf("\n b = %d", var.b);
}

Advantages of union

● It occupies less memory compared to the structure.


● When you use union, only the last variable can be directly accessed.
● Union is used when you have to use the same memory location for two or more data
members.
● It enables you to hold data of only one data member.
Enumerated data type

● Enumeration (or enum) is a user defined data type in C.


● It is mainly used to assign names to integral constants, the names make a program
easy to read and maintain.

// An example program to demonstrate working of enum in C

#include<stdio.h>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}

Output:
2

// Another example program to demonstrate working of enum in C

#include<stdio.h>

enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};

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

File
A file is a container in computer storage devices used for storing data. Or, A File can be used
to store a large volume of persistent data.

Why are files needed?


● When a program is terminated, the entire data is lost. Storing in a file will preserve
your data even if the program terminates.
● If you have to enter a large amount of data, it will take a lot of time to enter them all.
● However, if you have a file containing all the data, you can easily access the contents
of the file using a few commands in C.
● You can easily move your data from one computer to another without any changes.

Types of Files

1. Text files
● Text files are the normal .txt files.
● You can easily create text files using any simple text editors such as Notepad.
● When you open those files, you'll see all the contents within the file as plain text.
● You can easily edit or delete the contents.

2. Binary files
● Binary files are mostly the .bin files in your computer.
● Instead of storing data in plain text, they store it in the binary form (0's and 1's).

The following operations can be performed on a file.

Creation of the new file


Opening an existing file
Reading from the file
Writing to the file
Deleting the file

Following are the most important file management functions:-


How to Create a File:-
Whenever you want to work with a file, the first step is to create a file. A file is nothing but
space in a memory where data is stored.

FILE *fp;
fp = fopen ("file_name", "mode");

fopen is a standard function which is used to open a file.

● If the file is not present on the system, then it is created and then opened.
● If a file is already present on the system, then it is directly opened using this function.
Example:

#include <stdio.h>
int main() {
FILE *fp;
fp = fopen ("[Link]", "w");
}

How to Close a file:-


● One should always close a file whenever the operations on file are over. It means the
contents and links to the file are terminated. This prevents accidental damage to the
file.
Syntax:
fclose (file_pointer);

Example:

FILE *fp;
fp = fopen ("[Link]", "r");
fclose (fp);

Writing to a File:-

Library functions to write to a file:


● fputc(char, file_pointer): It writes a character to the file pointed to by file_pointer.
● fputs(str, file_pointer): It writes a string to the file pointed to by file_pointer.
● fprintf(file_pointer, str, variable_lists): It prints a string to the file pointed to by
file_pointer. The string can optionally include format specifiers and a list of variables
variable_lists.

Reading data from a File:-

● fgetc(file_pointer): It returns the next character from the file pointed to by the file
pointer. When the end of the file has been reached, the EOF is sent back.
● fgets(buffer, n, file_pointer): It reads n-1 characters from the file and stores the string
in a buffer in which the NULL character ‘\0’ is appended as the last character.
● fscanf(file_pointer, conversion_specifiers, variable_adresses): It is used to parse and
analyze data. It reads characters from the file and assigns the input to a list of variable
pointers variable_adresses using conversion specifiers. Keep in mind that as with
scanf, fscanf stops reading a string when space or newline is encountered.

Command Line Arguments

● It is possible to pass some values from the command line to C programs when they
are executed.
● These values are called command line arguments.
● The command line arguments are handled using main() function arguments where
argc refers to the number of arguments passed, and argv[] is a pointer array which
points to each argument passed to the program.

Example:-
#include <stdio.h>

int main( int argc, char *argv[] ) {

if( argc == 2 ) {
printf("The argument given is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments given.\n");
}
else {
printf("One argument expected.\n");
}
}
Output:-
./[Link] hai
The argument given is testing

./[Link]
One argument expected

Notes:
argc - argc (ARGument Count) is int and stores number of command-line arguments passed
by the user including the name of the program. So if we pass a value to a program, value of
argc would be 2 (one for argument and one for program name).

argv - argv(ARGument Vector) is array of character pointers listing all the arguments.

Common questions

Powered by AI

File management functions like `fopen`, `fclose`, `fgetc`, and `fputc` in C ensure data safety and integrity by allocating proper file pointers and managing file states appropriately. For instance, checking the return value of `fopen` avoids null pointers and potential segmentation faults; using `fclose` promptly releases resources, preventing file corruption or unintended locks . Recommended practices include checking for errors after each file operation, using proper file opening modes, maintaining strict read/write permissions, and ensuring files are properly closed even in error cases through careful structuring of error handlers and cleanup code.

Unions in C allow storing different data types in the same memory location, making them advantageous in memory-constrained environments. They are preferred where multiple members never need to hold values simultaneously. For example, a variable storing different formats of data (e.g., integer, float) at different times can benefit from a union to conserve memory. However, unions allow only one member to be accessed at a time , which can complicate scenarios where simultaneous access of multiple data types is required. Despite this limitation, unions can significantly optimize resource usage.

Passing structures by reference in C is done by passing pointers to structures as function arguments. This approach avoids copying large data structures, enhances performance, and enables the function to modify the original structure. The syntax involves using `&` to pass the address and `*` or `->` to access structure members. For example, `addNumbers(com c1, com c2, com *result)` function modifies `result` directly . This method saves memory usage and processing time since no data duplication occurs, unlike passing by value, which creates copies of the structure data.

An array of structures allows efficient handling of multiple related records by storing them contiguously in memory, which simplifies data management operations such as sorting or filtering. For instance, in a program that manages student records, an array of structures holding each student's data simplifies operations like sorting by name or computing averages. Using an array of structures avoids the redundancy and complexity of declaring and maintaining multiple individual structure variables, thus streamlining code and improving maintainability .

Pointers to structures in C are used to store the address of a structure, allowing indirect manipulation of structure members. This facilitates dynamic data handling. For example, you can declare a pointer to a structure like `struct person *personPtr`, and then assign it the address of a structure variable using `personPtr = &person1;` . You can access structure members using the arrow operator (`->`), such as `personPtr->age` . This allows for efficient data access and manipulation in scenarios such as linked lists or memory-efficient function calls.

Binary files in C offer advantages over text files by directly storing the byte representation of data, making them often smaller and faster for reading and writing than text files. They are advantageous in applications requiring precise control over data format, such as handling multimedia files or transferring data across different systems without conversion errors . These direct byte operations enable greater accuracy and speed for complex data such as images or compiled data formats, while text files require parsing or conversions that can introduce errors or slow processing.

Managing files in C involves a series of operations including opening a file, performing data operations (read/write), and then closing the file. Opening is done using `fopen`, which checks if the file exists and creates it if it does not; this precedes reading/writing to ensure the file is available and pointers are initialized correctly . Reading/writing then takes place using functions like `fgetc`, `fputc`, `fscanf`, and `fprintf`. Closing a file with `fclose` is crucial to release resources, avoid data corruption, and mitigate file lock issues . Following this sequence guarantees consistency and integrity of data during file operations.

Command line arguments increase the flexibility of C programs by allowing the user to pass additional parameters when executing the program, thus enabling dynamic behavior without changing the code. They are accessed via the `argc` and `argv` parameters in the main function, where `argc` represents the number of arguments and `argv` is an array of strings containing these arguments . However, pitfalls include ensuring correct number handling in `argc`, bounds-checking `argv` to prevent array overflows, and properly parsing string arguments which might not naturally convert to other data types without handling.

Enumerations in C serve as a way to assign meaningful names to integral constants, which enhances code readability by providing context to what values represent, making source code more understandable and easier to maintain. For example, using an enum for days of the week allows the code to use `Mon, Tue, Wed` instead of `0, 1, 2`, providing clear documentation of valid values without verbose comments . Enumerations also help prevent errors by limiting the set of possible values a variable can take.

Structures and unions in C are both user-defined data types that allow grouping of variables. However, a structure allocates separate memory space for each of its members, whereas a union uses a single memory space shared among all its members. This means that a union requires less memory compared to a structure because at any given time, only one member can store a value . The efficiency in memory usage makes unions suitable for situations where the same memory location needs to be used for storing multiple data types in different scenarios.

You might also like