Skip to content

Latest commit

 

History

History

chapter09

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Chapter 9 - Structures

Arrays and strings---------Similar data(int,float,char)
Structures can hold---------Dissimilar data

Syntax of creating structures

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.

Why use structures?

  • Structures keep the data organized
  • Structures make data management easy for the programmer

Array of structures

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;

Initializing structures

Structures can be initialized as follows:

struct employee rahul = {100,30.0,"rahul"}
struct employee sorabh = {0} // all elements set to 0

Structures in memory

Structures are stored in contiguous memory.
For an array of structures,instances of structures are stored in adjacent to each other.

Pointer to structures

A pointer to structure can be created as follows:-

struct employee *ptr;
ptr = &e1;

We can print structure as follows-

printf("%d",(*ptr).code);

Arrow operator

Instead of writing (*ptr).code, we can use

ptr->code = 101;

Passing structure to a function

A structure can be passed to a function just like any other data type.

void show(struct employee emp); // function prototype

Typedef keyword

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

Exercises

  1. Create a two dimensional vector using structures.
  2. Write a function sumvector which returns the sum of two vectors passed to it. The vectors must be two dimensional.
  3. Write a program to illustrate the use of arrow operator -> in C.
  4. Write a program with a structure representing a complex number.
  5. 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.
  6. Write problem 4's structure using typedef keyword.
  7. Create a structure representing a bank account of a customer. What fields did you use and why?
  8. Write a structure capable of storing date. Write a function to compare those dates.
  9. Solve problem 8 for time using typedef keyword.