0
0
Cprogramming~5 mins

Accessing structure members

Choose your learning style9 modes available
Introduction
Structures group related data together. Accessing structure members lets you use or change each piece of data inside the group.
When you want to store information about a person, like name and age, in one place.
When you need to keep details about a book, such as title, author, and pages.
When you want to organize data about a car, like model, year, and color.
When you want to pass multiple related values to a function easily.
When you want to read or update specific parts of grouped data.
Syntax
C
struct StructName {
    dataType member1;
    dataType member2;
    // more members
};

struct StructName variableName;

// Access members using dot operator
variableName.member1 = value;
value = variableName.member2;
Use the dot (.) operator to access members of a structure variable.
Make sure the structure variable is declared before accessing its members.
Examples
Here, we create a Person structure and set the age member to 25.
C
struct Person {
    char name[50];
    int age;
};

struct Person p1;
p1.age = 25;
We set the title and pages of a Book structure variable.
C
struct Book {
    char title[100];
    int pages;
};

struct Book b1;
strcpy(b1.title, "C Programming");
b1.pages = 300;
Sample Program
This program creates a Student structure, assigns values to its members, and prints them.
C
#include <stdio.h>
#include <string.h>

struct Student {
    char name[30];
    int grade;
};

int main() {
    struct Student s1;
    strcpy(s1.name, "Alice");
    s1.grade = 90;

    printf("Student Name: %s\n", s1.name);
    printf("Student Grade: %d\n", s1.grade);

    return 0;
}
OutputSuccess
Important Notes
Remember to include when copying strings into structure members.
Use strcpy() to copy strings into character arrays inside structures.
Access structure members with the dot operator only when you have a structure variable, not a pointer.
Summary
Structures group related data under one name.
Use the dot operator (.) to access or change structure members.
Assign values carefully, especially for strings inside structures.