Arrays and strings--------- | Similar data(int,float,char) |
Structures can hold--------- | Dissimilar data |
struct emp{ int code; float salery; // this declare a new user defined data type char name[10]; }; // semicolon is important
A structure in C is a collection of variables of different types under a single name.
2. Write a program to store the details of 3 employees from usr defined data.Use the structure declared above.
- Structures keep the data organized
- Structures make data management easy for the programmer
Just like an array of integers, an array of floats and an array of characters, we can create an array of structures.
struct employee facebook[100]; // array of structures // We can access the data using facebook[0].code = 100; facebook[0].salery = 12.5;
Structures can be initialized as follows:
struct employee rahul = {100,30.0,"rahul"}
struct employee sorabh = {0} // all elements set to 0
Structures are stored in contiguous memory.
For an array of structures,instances of structures are stored in adjacent to each other.
A pointer to structure can be created as follows:-
struct employee *ptr; ptr = &e1;
We can print structure as follows-
printf("%d",(*ptr).code);
Instead of writing (*ptr).code, we can use
ptr->code = 101;
A structure can be passed to a function just like any other data type.
void show(struct employee emp); // function prototype
We can use the typedef keyword to create an alias name for data types in C.
typedef is more commonly used with structures.
typedef struct complex { float real; int roll; char sd[30]; }complex; // defining
- Create a two dimensional vector using structures.
- Write a function sumvector which returns the sum of two vectors passed to it. The vectors must be two dimensional.
- Write a program to illustrate the use of arrow operator -> in C.
- Write a program with a structure representing a complex number.
- Create an array of 5 complex numbers created in problem 5 and display them with the help of a display function.The values must be taken as an input from the user.
- Write problem 4's structure using typedef keyword.
- Create a structure representing a bank account of a customer. What fields did you use and why?
- Write a structure capable of storing date. Write a function to compare those dates.
- Solve problem 8 for time using typedef keyword.