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
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›Structures: Defining Structures, Accessing Structure Member, Structures and Functions
    Programming FundamentalsTopic 28 of 39

    Structures: Defining Structures, Accessing Structure Member, Structures and Functions

    7 minread
    1,198words
    Intermediatelevel

    Structures in C: Defining Structures, Accessing Structure Members, and Structures and Functions

    In C, a structure is a user-defined data type that allows grouping of variables of different data types under a single name. This is useful when you need to represent a collection of related data as a single entity, such as information about a person, a student, a book, etc. Structures provide a way to organize and manage complex data more efficiently.

    Let’s explore the concept of structures in C, how to define and access them, and how to use them with functions.


    1. Defining Structures

    A structure is defined using the struct keyword followed by the structure name and a block containing the structure members. The members can be of different data types.

    Syntax for Defining a Structure:

    struct structure_name {
        data_type member1;
        data_type member2;
        // Additional members
    };
    

    Example: Defining a structure to store information about a student

    #include <stdio.h>
    
    // Defining a structure to represent a student
    struct Student {
        char name[50];    // Name of the student
        int age;          // Age of the student
        float grade;      // Grade of the student
    };
    
    int main() {
        // Declare a structure variable of type Student
        struct Student student1;
    
        // Assigning values to the members of student1
        strcpy(student1.name, "John Doe");
        student1.age = 20;
        student1.grade = 85.5;
    
        // Printing the values of student1
        printf("Student Name: %s\n", student1.name);
        printf("Student Age: %d\n", student1.age);
        printf("Student Grade: %.2f\n", student1.grade);
    
        return 0;
    }
    

    Explanation:

    • struct Student defines a structure with three members: name, age, and grade.
    • A variable student1 is created as an instance of the structure Student.
    • The strcpy() function is used to assign a string to the name member because arrays of characters (strings) cannot be directly assigned.

    Output:

    Student Name: John Doe
    Student Age: 20
    Student Grade: 85.50
    

    2. Accessing Structure Members

    Structure members are accessed using the dot operator (.). After declaring a structure variable, you can use this operator to access and modify its members.

    Example: Accessing and modifying structure members

    #include <stdio.h>
    
    struct Point {
        int x;
        int y;
    };
    
    int main() {
        struct Point point1;  // Declare a structure variable
    
        // Accessing structure members and assigning values
        point1.x = 10;
        point1.y = 20;
    
        // Accessing structure members and printing them
        printf("Point coordinates: (%d, %d)\n", point1.x, point1.y);
    
        return 0;
    }
    

    Explanation:

    • point1.x and point1.y access the x and y members of the structure point1, and we assign values to these members.
    • The values are then printed using printf().

    Output:

    Point coordinates: (10, 20)
    

    3. Structures and Functions

    You can pass structures to functions in C, either by value (copying the structure data) or by reference (using pointers to the structure). Let's see how structures are used in functions.

    3.1 Passing Structures to Functions by Value

    When a structure is passed to a function by value, the function gets a copy of the structure, meaning that changes made inside the function do not affect the original structure.

    Example: Passing a structure by value

    #include <stdio.h>
    
    struct Student {
        char name[50];
        int age;
        float grade;
    };
    
    // Function to print student details (passing by value)
    void printStudent(struct Student s) {
        printf("Student Name: %s\n", s.name);
        printf("Student Age: %d\n", s.age);
        printf("Student Grade: %.2f\n", s.grade);
    }
    
    int main() {
        struct Student student1 = {"Alice", 22, 90.5};
    
        // Passing structure to function by value
        printStudent(student1);
    
        return 0;
    }
    

    Explanation:

    • The structure Student is passed to the printStudent() function by value.
    • The structure is copied to the function, and the function prints the student's details.
    • Since the function receives a copy of the structure, any modifications inside the function won't affect the original structure.

    Output:

    Student Name: Alice
    Student Age: 22
    Student Grade: 90.50
    

    3.2 Passing Structures to Functions by Reference (Using Pointers)

    When a structure is passed by reference, the function works with the original structure. Any changes made inside the function will affect the original structure.

    Example: Passing a structure by reference using pointers

    #include <stdio.h>
    
    struct Student {
        char name[50];
        int age;
        float grade;
    };
    
    // Function to modify student details (passing by reference)
    void updateStudent(struct Student *s, const char *newName, int newAge, float newGrade) {
        // Modifying structure members using pointer
        strcpy(s->name, newName);
        s->age = newAge;
        s->grade = newGrade;
    }
    
    int main() {
        struct Student student1 = {"Alice", 22, 90.5};
    
        printf("Before Update:\n");
        printf("Student Name: %s\n", student1.name);
        printf("Student Age: %d\n", student1.age);
        printf("Student Grade: %.2f\n", student1.grade);
    
        // Passing structure to function by reference (using pointer)
        updateStudent(&student1, "Bob", 25, 95.0);
    
        printf("\nAfter Update:\n");
        printf("Student Name: %s\n", student1.name);
        printf("Student Age: %d\n", student1.age);
        printf("Student Grade: %.2f\n", student1.grade);
    
        return 0;
    }
    

    Explanation:

    • The function updateStudent() takes a pointer to a Student structure as an argument, which allows it to modify the original structure.
    • The s->name, s->age, and s->grade access the members of the structure through the pointer.
    • The original structure student1 is modified by the function because the address of student1 is passed.

    Output:

    Before Update:
    Student Name: Alice
    Student Age: 22
    Student Grade: 90.50
    
    After Update:
    Student Name: Bob
    Student Age: 25
    Student Grade: 95.00
    

    3.3 Returning Structures from Functions

    C functions can return structures, which allows functions to generate and return structured data.

    Example: Returning a structure from a function

    #include <stdio.h>
    
    struct Student {
        char name[50];
        int age;
        float grade;
    };
    
    // Function to create and return a student
    struct Student createStudent(const char *name, int age, float grade) {
        struct Student s;
        strcpy(s.name, name);
        s.age = age;
        s.grade = grade;
        return s;
    }
    
    int main() {
        // Creating a student by calling the function
        struct Student student1 = createStudent("Charlie", 20, 88.5);
    
        printf("Student Name: %s\n", student1.name);
        printf("Student Age: %d\n", student1.age);
        printf("Student Grade: %.2f\n", student1.grade);
    
        return 0;
    }
    

    Explanation:

    • The createStudent() function returns a Student structure by creating a structure, assigning values, and returning it.
    • The returned structure is assigned to student1, and its members are printed.

    Output:

    Student Name: Charlie
    Student Age: 20
    Student Grade: 88.50
    

    Summary

    • Defining Structures: Structures are defined using the struct keyword, and they can hold members of different data types.
    • Accessing Structure Members: You can access structure members using the dot operator (.).
    • Structures and Functions:
      • Structures can be passed by value (creating a copy) or by reference (using pointers).
      • You can modify the original structure if passed by reference.
      • Structures can also be returned from functions.

    Using structures in C allows you to group related data, making your programs more organized and easier to manage.

    Previous topic 27
    Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf
    Next topic 29
    typedef, Unions

    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,198
      Code examples0
      DifficultyIntermediate