6.1 C Struct
1. Introduction to struct
A struct in C is a user-defined data type that allows grouping of variables of different types under a single name. It is used to represent a collection of related data.
Example:
struct Person { char name[50]; int age; float height;};In this example, struct Person defines a structure with three members: name (a string), age (an integer), and height (a float). You can then create variables of type struct Person and access their members.
Usage:
struct Person person1;person1.age = 25;person1.height = 5.9;strcpy(person1.name, "Alice");struct Similar to Class ?
a struct in C is somewhat similar to a class in Python or Java, but with key differences:
Similarities:
- Both group related data together.
- You can access individual members (or attributes) using dot notation.
Differences:
-
No Methods: A
structin C only holds data (variables). It doesn’t have methods (functions) like a class in Python or Java. -
No Encapsulation: C
structmembers are always public, so there’s no concept of private or protected access modifiers. -
No Inheritance: C
structdoesn’t support inheritance, while classes in Python and Java do. -
Memory Management: C doesn’t have automatic memory management (like garbage collection in Java or Python). You must manage memory manually using
mallocandfreeif you’re using pointers inside astruct.
In short, while both are used to represent composite data types, classes in Python or Java are more powerful and feature-rich.
2. Syntax
2.1 Basic Usecase
/* Declaration of the struct */struct Person {char zName[10];int iAge;} p2, p4;
/* p2, p4 are variable of type `struct Person` */
/* Can create more varaibles out of the type `struct Person` */struct Person p1;2.2 Anonymous Struct
// Declaration of an anonymous struct and creating a variable at the same timestruct { /* <tag_name> is optional */char zName[4];int iAge;} p1, p2;
...
struct <???> p3;/* ERR: Cannot create a variable later using the anonymous struct above. This is because anonymous struct does not have a tag name */2.3 typedef a struct
/* Declaration of the struct */typedef struct { /* <tag_name> is optional */char zName[10];int iAge;} PersonType;
/* Create a variable out of the datatype 'PersonType' */PersonType p1;
strcpy(p1.zName, “Nadith”);p1.iAge = 30;
PersonType p2;