ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112Structures Definition …
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    7 min read
    Topic 28 of 39
    Topic Study Note Illustration
    28

    Structures: Defining Structures, Accessing Structure Member, 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...

    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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.2kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals