The content on this website, including videos and code examples, is for educational purposes only. All demonstrations and designs are fictional and created to illustrate coding techniques. Any resemblance to existing websites or brands is purely coincidental.
The creators and administrators of this website do not claim ownership or affiliation with any existing websites or companies. Users are encouraged to use the information responsibly for learning purposes. Liability for any misuse of the content provided is not accepted.
Structure: It is a user-defined data type that allows different data types to be combined to represent a data record.
Defining a structure: Unlike arrays, structures must be defined first for their format that may be used later to declare structure variables.
Note:
1) The template is terminated with a semicolon.
2) While the entire definition is considered as a statement, each member is declared independently for its name and is typed in a separate statement inside the template.
3) The tag name can be used to declare structure variables of its type, later in the program.
Arrays VS Structure: Both the arrays and structures are classified as structured data types as they provide a mechanism that enables us to access and manipulate data in a relatively easy manner. But they differ in several ways which are as follows:
1) An array is a collection of related data elements of the same type. The structure can have elements of different types.
2) An array is a derived data type whereas a structure is a programmer-defined one.
3) Any array behaves like a built-in data type. All we have to do is to declare an array variable and use it. But in the case of a structure, first, we have to design and declare a data structure before the variables of that type are declared and used.
Declaring structure variables: After defining a structured format we can declare variables of that type. A structure variable declaration is similar to the declaration of variables of any other data type. It includes the following elements:
1) The keyword struct.
2) The structure tag name.
3) List of variable names separated by commas.
4) A terminating semicolon.
Accessing Structure Members: There are multiple ways to access and assign values to members of the structure. As it is clear that members themselves are not variables. The link between a member and a variable is established using the member operator "." which is known as the "dot operator" or "period operator".
Structure Initialization: Like any other data type, a structure variable can be initialized at compile time.
Must have elements in compile-time initialization of a structure:
1) The keyword struct.
2) The structure tag name.
3) The name of the variable to be declared.
4) The assignment operator "=".
5) A set of values for the members of the structure variable, separated by commas and enclosed in braces.
6) A terminating semicolon.
Rules for Initializing structure:
1) We cannot initialize individual members inside the structure template.
2) The order of values enclosed in braces must match the order of members in the structure definition.
3) It is permitted to have a partial Initialization. We can initialize only the first few members and leave the remaining blank. The uninitialized members should be only at the end of the list.
4) The uninitialized members will be assigned default values as Zero for integer & floating point numbers and '\0' for characters & strings.
Copying and Comparing Structure Variables: Two variables of the same structure type can be copied in the same way as ordinary variables. However, any logical operations are not permitted on structure variables. In that case, we can do so by comparing members individually.
Word Boundaries and Slack Bytes: Computer stores structures using the concept of "word boundary". The size of a word boundary is machine-dependent. In a computer with two bytes word boundary, the members of a structure are stored left aligned on the word boundary, as shown below. A character data takes one byte and an integer takes two bytes. One byte between them is left unoccupied. This unoccupied byte is known as the slack byte.
Arrays of Structure: The array of structure is declared just as it would have been with any other array. It is stored inside the memory in the same way as a multi-dimensional array.
Arrays within structures: C permits the use of arrays as structure members. As we have already seen a char array in the same way we can use int, float or any other data type.
Structures Within Structures: It means the nesting of structures.
Note: C permits nesting up to 15 levels.
Structures and Functions: There are three methods by which the values of a structure can be transferred from one function to another.
1) It involves passing each member of the structure as an actual argument of the function call. This becomes unmanageable and inefficient when the structure size is large.
2) It involves passing a copy of the entire structure to called function. so this function needs to return the whole structure to work properly. All compilers may not support this method.
3) It involves the use of pointers to pass the structure as an argument. More efficient than method 2.
Passing a copy of the whole structure as a parameter (Note):
1) The called function must be declared for its type, appropriate to the data type it is expected to return. For example, if it returns a copy of the entire structure, then it must be declared as a struct with an appropriate tag name.
2) The structure variable used as the actual argument and the corresponding formal argument in the called function must be of the same struct type.
3) The return statement is necessary only when the function is returning some data to the calling function. The expression may be any simple variable or structure variable or an expression using simple variables.
4) When a function returns a structure, it must be assigned to a structure of identical type in the calling function.
5) The called functions must be declared in the calling function appropriately.
Unions: Unions are a concept borrowed from structures and therefore follow the same syntax as structures. However, there is a major distinction between them in terms of storage. In structures, each member has its storage location, whereas all the members of a union use the same location. This implies that, although a union use the same location. This implies that, although a union may contain many members of different types, it can handle only one member at a time. Like structures, a union can be declared using the keyword union.
Size of Structure: The actual size of these variables in terms of bytes may change from machine to machine. We may use the unary operator sizeof to tell us the size of a structure (or any variable).
Accessing the structure member:
accessing_the_structure_member.c
#include <stdio.h>
struct book_details {
char book_title[20];
int book_price;
};
void main() {
struct book_details book1;
printf("Enter the title of book: ");
scanf("%s", book1.book_title);
printf("\nEnter the price of book: ");
scanf("%d", &book1.book_price);
printf("\nDetails Entered:\n\tTitle of Book: %s\n\tPrice of book: %d", book1.book_title, book1.book_price);
}
Initialising of structure:
initialising_of_structure.c
#include <stdio.h>
struct student_detail {
int weight;
float height;
} student1 = {160, 170.5};
void main() {
struct student_detail student2 = {80, 150.25};
printf("Student 1: \n\tweight: %d\t\tHeight: %0.2f", student1.weight, student1.height);
printf("\nStudent 2: \n\tweight: %d\t\tHeight: %0.2f", student2.weight, student2.height);
}
Copying and comparing the structure:
copying_and_comparing_the_structure.c
#include <stdio.h>
struct person {
char name [10];
int age;
};
void main() {
int temp_compare_age;
struct person p1 = {"ABC", 20} ;
struct person p2 = {"XYZ", 30};
struct person p3;
p3 = p2; // copying p2 in p3
temp_compare_age = (p3.age = p2.age) ? 1 : 0; // comparing member of structure
temp_compare_age = 1 ? printf("P2 and P3 are Same.\n\tName: %s\t\tAge: %d", p3.name, p3.age) : printf("P2 and P3 are different.");
}
Array of structure:
array_of_structure.c
#include <stdio.h>
struct student_marks {
int sub1;
int sub2;
int total;
};
void main() {
int i;
struct student_marks sm[2] = {{2, 2, 0}, {1, 2, 0}};
for (i = 0; i < 2; i++)
sm[i].total = sm[i].sub1 + sm[i].sub2;
printf("Student\t\tSubject1\tSubject2\tTotal\n");
for (i = 0; i < 2; i++)
printf("Student %d\t%d\t\t%d\t\t%d\n", i + 1, sm[i].sub1, sm[i].sub2, sm[i].total);
}
Array within structure:
array_within_structure.c
#include <stdio.h>
struct student_marks {
int sub[2];
int total;
};
void main() {
struct student_marks sm[2] = {{14, 4, 0}, {3, 6, 0}};
int i, j;
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
sm[i].total += sm[i].sub[j];
printf("Student\t\tTotal\n");
for (i = 0; i < 2; i++) {
printf("Student %d\tTotal: %d\n", i + 1, sm[i].total);
for (j = 0; j < 2; j++)
printf("\t\tSubject %d Marks: %d\n", j + 1, sm[i].sub[j]);
printf("\n");
}
}
Structure within structure:
structure_within_structure.c
#include <stdio.h>
struct person {
struct {
char first_name [10];
char last_name [10];
} name;
int age;
};
void main() {
struct person p;
printf("Enter name (use space between first and last name): ");
scanf("%s", p.name.first_name);
scanf("%s", p.name.last_name);
printf("\nEnter age: ");
scanf("%d", &p.age);
printf("\nDetails: \n\tName: %s %s\n\tAge: %d", p.name.first_name, p.name.last_name, p.age);
}
Passing structure as parameter in function:
passing_structure_as_parameter_in_function.c
#include <stdio.h>
struct store {
char product_name[20];
float product_price;
int quantity_of_product;
};
struct store update(struct store p, float p_price, int q_product);
float mul(struct store stock);
void main() {
float p_increment, value;
int q_increment;
struct store product = {"product1", 25.75, 12};
printf("\nInput increment values: \n\tPrice and Quantity:");
scanf("%f %d", &p_increment, &q_increment);
product = update(product, p_increment, q_increment);
printf("\nUpdated values of product\n\tName: %s\n\tPrice: %0.2f\n\tQuantity: %d\n",
product.product_name, product.product_price, product.quantity_of_product);
value = mul(product);
printf("\nTotal Price of Product = %0.2f", value);
}
struct store update(struct store p, float p_price, int q_product) {
p.product_price += p_price;
p.quantity_of_product += q_product;
return (p);
}
float mul(struct store stock) {
return (stock.product_price * stock.quantity_of_product);
}