Structure
Structure
PROGRAMMING IN C
PREPARED BY,
Mrs.R.MOHANA,
MCA-MEC.
Structure
struct structure_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.
struct employee
{
int id;
char name[20];
float salary;
};
The size of the datatype depends on the type of
machine .
struct structure_name
{
data_type member_name1;
data_type member_name1;
….
….
}variable1, varaible2, …;
EXAMPLE:
struct student
{
int rollno;
char name[20];
}stud1,stud2;
struct student
{
int rollno;
char name[20];
};
Syntax
structurename.member1;
strcuturename.member2;
//Program example to declare a Structure, structure member and access a
Structure varaible:
#include <stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[20];
};
void main()
{
struct student s1;
s1.rollno = 101;
s1.name=”Raksha”;
printf(“%d”,s1.rollno);
printf(“%s”,s1.name);
}
Here a structure is defined called a student,
which consists of a rollno and a name for its
members.
For example:
struct student
{
int roll_no;
char name[20];
int age;
};
………….
struct student s1={1,”vansh”,23};
For Example:
S[0].x=5;
S[0].y=7;
S[1].x=7;
S[1].y=9;
S[2].x=9;
S[2].y=10;
// Program example to demonstrate Array of Structures
#include<stdio.h>
#include<conio.h>
struct student
{
char name[30];
int roll;
float marks;
};
void main()
{
struct student s[3];
int i;
for(i=0;i< 3;i++)
{
printf(“Enter name, roll and marks of student:\n”);
scanf(“%s%d%f”,s[i].name, &s[i].roll, &s[i].marks);
}
for(i=0;i< 3;i++)
{
printf(“Name: %s\n”,s[i].name);
printf(“Roll: %d\n”, s[i].roll);
printf(“Marks: %0.2f\n\n”, s[i].marks);
}
getch();
}
struct car
{
char make[20]; Inside the Memory
char model[30];
int year;
};
struct car
arr_car[10];
POINTER TO STRUCTURE
For representing complex data structures , we
can use structures and pointers together.
Pointer can be member of structure , or pointer to
structure , or an array of pointers to str.
return 0;
}
Output:
Enter the Roll Number of Student
27
Enter Name of Student
Kamlesh_Joshi
Enter Branch of Student
Computer_Science And Engineering
Enter batch of Student
2019
Roll No: 27
Name: Kamlesh_Joshi
Branch: Computer_Science_And_Engineering
Batch: 2019
Nested Structure in C
struct outer_struct
{
outer_member1;
outer_member2;
struct inner_struct
{
inner_member1;
inner_member2;
} innervariable;
};
Example –
struct college
{
int numberOfStudents;
int numberOfTeachers;
struct student
{
char name[50];
int class;
int roll_Number;
} std;
};
In the above example of nested structure in C, there are
two structures Student (depended structure) and another
structure called college(Outer structure).
struct college c;
c.std.name=”OJ”;
c.std.class = 10;
c.std.roll_Number = 1;
Self-referential Structures
They are extensively used to build complex and dynamic data structures
such as linked lists and trees.
EXAMPLE:
int main()
{
// Declare variables using the typedef'd alias
UnshInt x = 10;
UnshInt y = 20;
UnshInt sum = x + y;
printf("The sum of %d and %d is %hu\n", x, y, sum);
return 0;
}
#include <stdio.h>
typedef int myint; // Define a new type name myint for the int data type
int main()
{
int x;
myint y; // Declare a variable y of type myint
typedef myint smallint; // Define a new type name smallint as an alias for
myint
smallint z;
printf("Enter 2 values: "); // Prompt the user to enter two values
scanf("%d %d", &x, &y);
z = x + y; // Calculate the sum of x and y and store the outcome in variable z
printf("Sum value is: %d", z); // Print the sum value
return 0;
}
Output:
Enter 2 values: 7 9
Sum value is: 16
Structure & typedef In C
We can use the typedef in C to create aliases for structure types and
define shorter, more descriptive names for these structures.
Syntax:
// Define a structure
struct structure_name
{
// Member variables
data_type member1;
data_type member2;
// ...
};
// Create an alias (typedef) for the structure
typedef struct structure_name alias_name;
struct structure_name: This is the name of the structure
being defined.
{ ... }: Within the curly braces, you list the member variables
of the structure.
#include <stdio.h>
// Define a structure to represent a point in 2D space
struct Point
{
int x;
int y;
};
int main()
{
Point2D p1 = {3, 5}; // Declare a variable of type Point using the typedef'd alias
// Access and print the coordinates of the point
printf("Coordinates of point p1: (%d, %d)\n", p1.x, p1.y);
return 0;
}
Output: Coordinates of point p1: (3, 5)
Pointers & typedef In C
Syntax:
// Define a typedef for a pointer type
typedef existing_type* alias_name;
typedef: This keyword is used to create an alias for the pointer type.
existing_type*: This represents the existing pointer type that you want
to alias. It could be any valid pointer type.
alias_name: This is the alias you're creating for the pointer type. It can
be any valid C identifier.
Example:
#include <stdio.h>
#include <stdlib.h> // Include the header file for malloc and free
int main() {
// Declare a variable of type IntPtr
IntPtr ptr;
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1; // Return error code
}
// Assign a value to the allocated memory
*ptr = 42;
return 0;
}
Output:
Value stored at memory location 0xa002a0: 42
Union
A union in C programming is a user-defined data type that allows different
types of data to be stored in the same memory location.
Union can only hold the value of one of its members at any given time.
Syntax
union UnionName
{
member1_type member1_name;
member2_type member2_name;
// ... additional members ...
};
The union keyword indicates that we are declaring a union construct
whose name/ identifier is given by UnionName.
The terms member1_type and member2_type refer to the data types of the
members of the union. These can be different data types.
// Define a union named Data with three members: int, float, and char
union Data
{
int i;
float f;
char c;
};
int main()
{
// Declare a union variable named myUnion
union Data myUnion;
/* Reprinting the value of union member i, but since all members of a union share the
same memory space this will lead to undefined behavior since the last value assigned
was to member c */
printf("Integer value: %d\n", myUnion.i);
return 0;
}
Output:
Integer value: 42
Float value: 3.140000
Character value: A
Integer value: 1078523201
Creating Variable Outside Main
This method allows you to define the union and create a
variable of that type in one block.
Syntax:
union UnionName
{
member1_type member1_name;
// Additional members, if any
};
union UnionName variableName;
Different Syntax for Initialization of Members of a Union
in C:
var1.member1 = value;
#include <stdio.h>
int main()
{
union Person person = { .age = 25 };
printf("Age: %d\n", person.age); // Output: Age: 25
return 0;
}
Output:
Age: 25
Accessing Members Pointer
Accessing members of a union in C with the arrow pointer (->) is
used when the union variable is a pointer.
It involves first declaring a pointer variable of the union type and
then using the arrow operator to access and manipulate its members.
Syntax:
//Declaring a pointer type union variable
union UnionName *ptrVariable;
int main()
{
union Shape *ptrShape; // Declare a pointer to a union variable
// Allocate memory for the union variable
ptrShape = (union Shape *)malloc(sizeof(union Shape));
ptrShape->sides = 4; // Access and assign value to union member using
arrow operator
printf("Number of sides: %d\n", ptrShape->sides); // Print the value of
the union member
free(ptrShape); // Free allocated memory
return 0;
}
Structures offer better type safety and clarity in code due to their explicit
declaration of multiple members.
Union require careful handling to ensure that the correct member is accessed
or modified at any given time.
File Handling
In C, you can create, open, read, and write to files by declaring a pointer of
type FILE, and use the fopen() function:
FILE *fptr;
fptr = fopen(filename, mode);
FILE is basically a data type, and we need to create a pointer variable to work
with it (fptr).
For now, this line is not important. It's just something you need when working
with files.
To actually open a file, use the fopen() function, which takes two parameters:
Filename-The name of the actual file you want to open (or create),
like filename.txt mode - A single character, which represents what
you want to do with the file (read, write or append):
w - Writes to a file
a - Appends new data to a file
r - Reads from a file
Create a File(open a file)
To create a file, you can use the w mode inside the fopen() function.
The w mode is used to write to a file. However, if the file does not exist,
it will create a file.
fclose() -- This will close the file when we are done with it.
FILE *fptr;
// Create a file
fptr = fopen("filename.txt", "w");
Example
FILE *fptr;
Next, we need to create a string that should be big enough to store the content of the file.
For example, let's create a string that can store up to 100 characters:
Example
FILE *fptr;
Example
fgets(myString, 100, fptr);
The first parameter specifies where to store the file content, which
will be in the myString array we just created.
The third parameter requires a file pointer that is used to read the
file (fptr in our example).
EXAMPLE:
FILE *fptr;
OUTPUT:
Hello World!
Hi everybody!
THANK YOU