Chapter 11C Language Tutorial~1 min read
Structures in C
Structures — Custom Data Types
Structure (struct) म्हणजे different data types एकत्र करून एक custom type बनवणे. एका student चे name, age, marks एकत्र ठेवायला struct वापरतात. C++ आणि Python च्या class चे ancestor!
Marathi Analogy
Struct म्हणजे Aadhar Card form सारखे. एकाच form मध्ये name (string), age (int), address (string), DOB (date) — वेगवेगळ्या types एकत्र. प्रत्येक माणसाचा स्वतःचा form (object) असतो.
Struct define आणि वापरणे
c
#include <stdio.h>
#include <string.h>
// Struct definition — type बनवणे
struct Student {
char name[50];
int age;
float marks;
char grade;
};
int main() {
// Struct variable declare करणे
struct Student s1;
// Members assign करणे
strcpy(s1.name, "Rahul Patil");
s1.age = 20;
s1.marks = 87.5;
s1.grade = 'A';
// Members access करणे — dot (.) operator
printf("Name: %s\n", s1.name);
printf("Age: %d\n", s1.age);
printf("Marks: %.1f\n", s1.marks);
printf("Grade: %c\n", s1.grade);
return 0;
}Struct Initialization आणि Array
Multiple students — struct array
c
#include <stdio.h>
#include <string.h>
struct Student {
char name[50];
int marks;
};
int main() {
// Initialization at declaration
struct Student s1 = {"Priya", 92};
struct Student s2 = {"Rahul", 78};
// Array of structs — multiple students
struct Student class[3] = {
{"Amit", 85},
{"Sneha", 91},
{"Ravi", 73}
};
// Loop करून print
for (int i = 0; i < 3; i++) {
printf("%s: %d\n", class[i].name, class[i].marks);
}
return 0;
}typedef — Shorter Name
typedef — struct साठी short alias
c
#include <stdio.h>
// typedef वापरून "struct Point" ऐवजी फक्त "Point"
typedef struct {
float x;
float y;
} Point;
typedef struct {
char name[50];
int age;
float marks;
} Student;
int main() {
// आता "struct Student" ऐवजी "Student" लिहायला चालते
Student s = {"Rahul", 20, 88.5};
Point p = {3.0, 4.0};
printf("%s, age %d, marks %.1f\n", s.name, s.age, s.marks);
printf("Point: (%.1f, %.1f)\n", p.x, p.y);
return 0;
}✅ Key Points — लक्षात ठेवा
- ▸struct — different types एकत्र करणे
- ▸struct members . (dot) operator ने access
- ▸struct variable declaration: struct TypeName varName;
- ▸typedef — struct ला short name देतो
- ▸Array of structs — multiple records एकत्र
0/12 chapters पूर्ण