ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CSI-311
    Progress0 / 17 topics
    Topics
    1. Overview of Computers and Programming2. Overview of Languages (e.g., C Language)3. Basics of Structured and Modular Programming4. Basic Algorithms and Problem Solving5. Development of Basic Algorithms6. Analyzing Problems7. Designing Solutions8. Testing Designed Solutions9. Fundamental Programming Constructs10. Translation of Algorithms to Programs11. Data Types12. Control Structures13. Functions14. Arrays15. Records16. Files17. Testing Programs
    CSI-311›Records
    Programming FundamentalsTopic 15 of 17

    Records

    7 minread
    1,264words
    Intermediatelevel

    Records in C Language (Structures)

    In C programming, a record is typically referred to as a structure (or struct). A structure is a user-defined data type that allows you to group different types of data under one name. Unlike arrays, which store elements of the same type, structures can store elements of different types. This makes structures ideal for representing more complex data models, such as records in a database, student information, employee details, etc.

    A structure is similar to an object in object-oriented programming, but it is simpler and does not have methods associated with it.


    1. Declaring a Structure

    In C, a structure is declared using the struct keyword followed by the structure name and the members (or fields) it will contain. Each member can be of any valid data type.

    • Syntax:

      struct structure_name {
          data_type member1;
          data_type member2;
          // other members
      };
      
    • Example:

      struct Student {
          char name[50];
          int age;
          float grade;
      };
      

    Here, we have declared a structure Student that contains three members:

    1. name – an array of characters (string) to store the student's name.
    2. age – an integer to store the student's age.
    3. grade – a float to store the student's grade.

    2. Accessing Structure Members

    To access the members of a structure, you use the dot (.) operator.

    • Syntax:

      structure_variable.member_name;
      
    • Example:

      struct Student student1;
      strcpy(student1.name, "John Doe");
      student1.age = 20;
      student1.grade = 85.5;
      
      printf("Name: %s\n", student1.name);
      printf("Age: %d\n", student1.age);
      printf("Grade: %.2f\n", student1.grade);
      

    In the example above:

    • We create a structure variable student1.
    • We assign values to the members using the dot operator: student1.name, student1.age, and student1.grade.

    3. Initializing a Structure

    You can initialize a structure at the time of declaration by assigning values to its members. If you initialize a structure, you need to provide values in the same order as the members are declared in the structure.

    • Syntax:

      struct structure_name structure_variable = {value1, value2, ...};
      
    • Example:

      struct Student student1 = {"Alice", 22, 90.5};
      

    Here, student1 is initialized with the name "Alice", age 22, and grade 90.5.


    4. Pointers to Structures

    You can create pointers to structures, which are often used when working with dynamic memory allocation or passing structures to functions.

    • Syntax for declaring a pointer to a structure:

      struct structure_name *pointer_name;
      
    • Example:

      struct Student *ptr;
      struct Student student1 = {"Bob", 21, 88.2};
      ptr = &student1;  // Assign address of student1 to ptr
      
      // Accessing members through the pointer using the arrow (->) operator
      printf("Name: %s\n", ptr->name);  // Output: Bob
      printf("Age: %d\n", ptr->age);    // Output: 21
      printf("Grade: %.2f\n", ptr->grade);  // Output: 88.20
      

    In the example above, ptr is a pointer to the Student structure. To access the members of a structure through a pointer, you use the arrow (->) operator instead of the dot (.) operator.


    5. Nested Structures

    Structures can contain other structures as members. This is known as nesting of structures. This feature is useful when you want to group more complex data types together.

    • Example:
      struct Date {
          int day;
          int month;
          int year;
      };
      
      struct Employee {
          char name[50];
          struct Date birthdate;  // Nested structure
          float salary;
      };
      

    In the above example, the Employee structure contains a member birthdate, which is itself a structure of type Date. This allows for hierarchical organization of data.

    • Accessing Nested Structure Members: You access the members of a nested structure using a combination of the dot operator (.) and the structure variable.

      struct Employee emp1 = {"John", {15, 8, 1990}, 50000.0};
      
      printf("Employee Name: %s\n", emp1.name);
      printf("Birthdate: %02d/%02d/%d\n", emp1.birthdate.day, emp1.birthdate.month, emp1.birthdate.year);
      printf("Salary: %.2f\n", emp1.salary);
      

    6. Arrays of Structures

    Just like arrays of primitive data types, you can create arrays of structures. This is useful when you need to store multiple records of the same type, such as a list of students or employees.

    • Syntax:

      struct structure_name array_name[array_size];
      
    • Example:

      struct Student students[3] = {
          {"Alice", 20, 85.5},
          {"Bob", 21, 90.0},
          {"Charlie", 22, 92.5}
      };
      

    In this example, we create an array of 3 Student structures, each initialized with values for name, age, and grade.

    • Accessing Array of Structures: You can access the members of an array of structures using the dot operator, just like with individual structures.

      printf("Name: %s, Age: %d, Grade: %.2f\n", students[0].name, students[0].age, students[0].grade);
      

    7. Functions with Structures

    Structures can be passed to functions either by value or by reference (using pointers). When passing a structure to a function, it's often more efficient to pass a pointer to the structure to avoid copying the entire structure.

    Passing by Value:

    • Example:
      void display(struct Student stu) {
          printf("Name: %s, Age: %d, Grade: %.2f\n", stu.name, stu.age, stu.grade);
      }
      
      int main() {
          struct Student student1 = {"Alice", 20, 85.5};
          display(student1);  // Pass by value
          return 0;
      }
      

    Passing by Reference (using pointers):

    • Example:
      void updateGrade(struct Student *stu, float newGrade) {
          stu->grade = newGrade;  // Modify grade through pointer
      }
      
      int main() {
          struct Student student1 = {"Bob", 22, 88.5};
          updateGrade(&student1, 95.0);  // Pass by reference
          printf("Updated Grade: %.2f\n", student1.grade);  // Output: 95.00
          return 0;
      }
      

    In the second example, the updateGrade function modifies the grade of student1 by passing a pointer to the structure.


    8. Structure Padding and Memory Alignment

    In C, compilers often introduce padding to align data in memory for efficient access. This can lead to the size of a structure being larger than the sum of the sizes of its individual members.

    For example:

    struct A {
        char a;   // 1 byte
        int b;    // 4 bytes
    };
    

    The total size of struct A might not be 5 bytes (1 byte + 4 bytes). It could be padded to 8 bytes for alignment reasons, as some architectures prefer variables of certain types (like int) to be aligned to specific memory boundaries.

    You can use the sizeof operator to check the size of a structure:

    printf("%lu\n", sizeof(struct A));  // Output might be 8, depending on the platform
    

    9. Summary of Structures (Records) in C

    • Definition: A structure is a user-defined data type that groups different data types together under one name.
    • Declaration: Use the struct keyword followed by the structure name and its members.
    • Accessing Members: Use the dot operator (.) for structure variables and the arrow operator (->) for structure pointers.
    • Nesting Structures: Structures can contain other structures as members.
    • Arrays of Structures: You can create arrays of structures to store multiple records.
    • Passing Structures to Functions: Structures can be passed by value or by reference (using pointers).
    • Padding and Memory Alignment: Structures might have padding between members for memory alignment, which can affect their size.

    Structures are essential for organizing related data in a clear and efficient way and are widely used in C for modeling real-world entities, like records in databases or objects in more complex systems.

    Previous topic 14
    Arrays
    Next topic 16
    Files

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,264
      Code examples0
      DifficultyIntermediate