0% found this document useful (0 votes)
35 views11 pages

Lecture7 C Structure Pointers

Uploaded by

saidurislam7733
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views11 pages

Lecture7 C Structure Pointers

Uploaded by

saidurislam7733
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Structure in C

What is a Structure?

 A user-defined data type in C that allows us to combine variables of


different data types under a single name.

 Why use Structures?


 Organize complex data
 Keep related information together
 Example: Storing student details, employee info, etc.
3

Array Vs Structure
4

Rules for Initializing Structures

1. Structure variables can be initialized at the time of declaration.


Example: struct Student s1 = {101, "Rahim", 3.75};

2. Values must follow the order of member declaration.


Example: struct Student s2 = {102, "Karim", 3.90}; // id → name → cgpa

3. Character arrays (strings) require double quotes " " for initialization.

4. Designated initializers are used to assign specific members of a structure,


while any member not assigned is set to 0 by default.
Example: struct Student s4 = {.name="Sadia", .cgpa=3.85}; // id defaults to 0

5. Multiple structure variables can be initialized in a single statement.


Example: struct Student s5 = {104,"Rafi",3.70}, s6 = {105,"Nabila",3.95};

6. Pointers to structures can be initialized using the address of a structure


variable.
Example: struct Student *ptr = &s1;
5
Example: Simple Structure in C

Steps
1. Structure declaration
2. Declaring Structure variable
3. Assigning values to structure
members.
4. Printing the values

OUTPUT
Example: Search Student by ID
6
7

Pointer to Structure in C
 A pointer to a structure is a variable that stores the address of a
structure variable.
 It allows us to access the members of the structure indirectly.

 Why use pointers with structures?


 Efficient memory usage → pass structures to functions without copying
whole structure
 Dynamic memory allocation → create structures at runtime
 Useful for linked lists, trees, and other data structure
8

Structure Member Access in C


Two Ways to Access Members

1. Dot Operator (.)


 Used with normal structure variable.
 Syntax: variable.member
 Example: s.roll

2. Arrow Operator (->)


 Used with pointer to structure.
 Syntax: pointer->member
 Shorthand for (*pointer).member
 Example: p->roll
9
Example: Two Ways to Access Structure Members
10

References

 Online resources
 Programming in ANSI: E Balagurusamy
Review Questions and Programming
Exercise (Chapter -10)

You might also like