Represent one record with several fields
An array groups values of one type. A structure groups named members that can have different types. Use a struct for a student record containing a roll number, a name and marks. Use a union only when one storage region intentionally holds one of several alternatives.
Structure example
#include
struct Student {
int roll;
char name[30];
double marks;
};
int main(void) {
struct Student student = {101, "Meena", 84.5};
struct Student *p = &student;
printf("%d %s %.1f\n", student.roll, student.name, student.marks);
p->marks = 86.0;
printf("updated=%.1f\n", student.marks);
return 0;
} Expected output is 101 Meena 84.5, then updated=86.0. The dot accesses a member of an object. The arrow accesses a member through a pointer: p->marks means (*p).marks.
Copying, comparing and layout
Assigning one structure to another of the same type copies its members, including array members. If a member is a pointer, the pointed-to allocation is not duplicated: both copies may refer to the same storage. Ownership rules still matter.
Structures can contain padding for alignment. sizeof(struct Student) need not equal the sum of the member sizes. Do not serialize a struct by assuming its raw byte layout will be portable across machines or compilers. Do not use memcmp as a general test of logical equality because padding bytes and representations can differ; compare the meaningful members.
Unions need a tag
enum ValueKind { INTEGER_VALUE, REAL_VALUE };
struct Value {
enum ValueKind kind;
union {
int integer;
double real;
} data;
};
struct Value item = {.kind = REAL_VALUE, .data.real = 3.5};The union's members overlap. Writing one member does not preserve independent values in all the others. The separate kind field records which member the program should interpret. A portable introductory design reads the member selected by that tag, rather than trying to reinterpret unrelated representations.
Passing records to functions
A structure passed by value is copied. For a read-only function, a parameter such as const struct Student *student avoids copying and prevents modification through that parameter. Check or document whether NULL is allowed.
Exercises
- Create an array of three students and print the one with the highest marks.
- Write a function to update marks through a struct pointer. Validate the range 0 to 100.
- Why can you assign entire structs but not ordinary arrays? Structure assignment is a language-supported operation that includes its array members.
- Add a text alternative to Value and describe how the tag prevents reading the wrong union member.
हिन्दी संकेत: struct के सभी members साथ रहते हैं; union के alternatives storage साझा करते हैं।