C Language Structures: Declaration, Initialization, and Member Access
Structure Declaration and Fundamentals
A structure is a composite data type that groups related variables under a single name. Each variable within a structure is called a member, and these members can have different data types.
The syntax for declaring a structure is:
struct structure_tag {
member_type1 member_name1;
member_type2 member_name2;
// additional members...
} variable_definitions;
For example, defining a studant record:
typedef struct Student {
char fullname[20];
int years_old;
char gender[5];
char student_id[20];
} StudentRecord;
Structure members can include scalar values, arrays, pointers, or even nested structures.
Defining and Initializing Structure Variables
After declaring a structure type, variables can be defined and initialized:
struct Coordinate {
int horizontal;
int vertical;
} point1;
struct Coordinate point2;
struct Coordinate point3 = {10, 20};
struct Person {
char person_name[15];
int person_age;
};
struct Person individual = {"John Doe", 25};
struct Element {
int value;
struct Coordinate location;
struct Element* link;
} node1 = {15, {7, 8}, NULL};
struct Element node2 = {25, {9, 10}, NULL};
Accessing Structure Members
Members of a structure variable are accessed using the dot operator (.):
struct DataContainer container;
strcpy(container.person_name, "Alice Smith");
container.person_age = 30;
When working with pointers to structures, members are accessed using the arrow operator (->):
struct Employee {
char employee_name[20];
int employee_age;
};
void display_info(struct Employee* emp_ptr) {
printf("Name: %s Age: %d\n", (*emp_ptr).employee_name, (*emp_ptr).employee_age);
printf("Name: %s Age: %d\n", emp_ptr->employee_name, emp_ptr->employee_age);
}
int main() {
struct Employee worker = {"Bob Johnson", 35};
display_info(&worker);
return 0;
}
Structure Passing to Functions
Structures can be passed to functions either by value or by address:
struct DataSet {
int large_array[1000];
int count;
};
struct DataSet dataset = {{5, 10, 15, 20}, 500};
void process_by_value(struct DataSet data) {
printf("Count: %d\n", data.count);
}
void process_by_reference(struct DataSet* data_ptr) {
printf("Count: %d\n", data_ptr->count);
}
int main() {
process_by_value(dataset);
process_by_reference(&dataset);
return 0;
}
Passing structures by reference is generally preferred for performence reasons. When passing large structures by value, the entire structure must be copied onto the stack, which can be computationally expensive. Passing a pointer instead requires only the memory address to be pushed on to the stack, resulting in better performance.