STRUCTURE
Structure is a derived data type in C.It is used to group together different data types under the same name.
syntax:
struct structure_name{
data_type1 variable_name1;
data_type2 variable_name2;
.......
.....
};
Are you confused? you could create a structure called customer,which is made up of a customer name, and customer contact number.
struct customer
{
char *name;
int number;
};
Note: the ; behind the last curly bracket.
you have created a new data type called customer. To access this data type ,you have to create a variable of the type customer.
struct customer customer1;
To access the members of structure ,you must use dot(".") operator like this ,
customer1.name = "john";
customer1.number = 123456789;
program:
#include<stdio.h>
struct customer
{
char *name;
int number;
};
int main()
{
struct customer customer1;
customer1.name = "John";
customer1.number = 123456789;
printf("Name: %s\n", customer1.name);
printf("Telephone number: %d\n", customer1.number);
return 0;
}
output:
Name: John
Telephone Number: 123456789
Use Of Structure:-
Structures are used to represent a record, like school, college student information. You might to track the following attributes about each student : Roll No., Name, Address,
Syntax of Structure:
Struct<structure_name>
{
<variable_list>;
};
Object of Structure:
Struct<structure_name><object_name>;
Rules for Structure:
1. The structure should be declared before main function or inside the main function.
2. In the structure there is input, output, mathematical, initialization, arrays the statements are not allowed only char single dimensional array.
3. The element of structure is access by only object of the structure.
STRUCTURE WITH ARRAY:
When we have to store a large number of records in a structure then we need a lot of structure variables. To overcome this problem we can define an array of structure. An array of structures can be defined in the following way:
NESTED STRUCTURE:
A structure is a collection of different data items. However sometimes we need to access a structure within some other structure. This can be achieved with the help of nested structures.
Pointers to Structs:
Sometimes it is useful to assign pointers to structures. Declaring pointers to structures is basically the same as declaring a normal pointer.
struct customer *customer1;
To dereference, you can use the infix operator: ->.
printf("%s\n", customer1->name
0 comments:
Post a Comment