Objectives
• Define anduse structures in C
• Explain the purpose of pointers
• Combine structures and pointers effectively
3.
What is aStructure?
- A structure is a user-defined data type in C.
- Groups different types of variables under a single name.
- Useful for representing real-world entities.
Syntax:
struct StructureName {
data_type member1;
data_type member2;
};
4.
Example of aStructure
#include <stdio.h>
struct Student {
int id;
char name[50];
float grade;
};
int main() {
struct Student s1 = {1, "Alice", 90.5};
printf("ID: %dn", s1.id);
printf("Name: %sn", s1.name);
printf("Grade: %.2fn", s1.grade);
return 0;
}
5.
What is aPointer?
- A pointer is a variable that stores the memory address of
another variable.
- Declared using * symbol.
- Useful for dynamic memory allocation and efficient data
manipulation.
Example:
int a = 10;
int *p = &a;
printf("Value of a: %dn", *p);
6.
Example of aPointer
#include <stdio.h>
int main() {
int a = 10; // Normal integer variable
int *p; // Pointer to integer
p = &a; // Store address of 'a' in pointer 'p'
// Display values
printf("Value of a: %dn", a); // Direct access
printf("Address of a: %pn", &a); // Address of variable a
printf("Value stored in pointer p: %pn", p); // Same address stored in pointer
printf("Value pointed to by p: %dn", *p); // Dereferencing
return 0;
}
7.
Structures with Pointers
Wecan use pointers to access structures.
Syntax:
struct StructName *ptr;
ptr = &variable;
Access members with:
. (dot operator) → Direct access
-> (arrow operator) → Pointer access
Key Takeaways
• Structuresgroup related data of different
types.
• Pointers allow direct memory manipulation.
• Pointers to structures are powerful for
functions and dynamic allocation.
• Use . for normal access and -> for pointer
access.
11.
Practice Activity
• Createa structure Book with fields: title,
author, price.
• Use a pointer to display book details.
Editor's Notes
#9 #include <stdio.h>
// Define a structure named "Student"
struct Student {
int id; // Member to store student ID
char name[50]; // Member to store student name (string)
};
// Function that accepts a pointer to a Student structure
void printStudent(struct Student *s) {
// Use -> operator because s is a pointer to a struct
printf("ID: %d\n", s->id);
printf("Name: %s\n", s->name);
}
int main() {
// Create a structure variable and initialize values
struct Student s1 = {3, "Charlie"};
// Pass the address of s1 to the function
// (&s1 means we are passing a pointer, not the full structure)
printStudent(&s1);
return 0; // Program ends successfully
}