How to define and use pointers to structures in the C language.
Below are the definition and usage methods of C language structure pointers.
- Define a structure type: First, it is necessary to define a structure type that can contain multiple fields (member variables).
For example, define a struct type that represents student information.
struct Student {
char name[50];
int age;
float score;
};
- Declare a pointer variable of a struct: Use the defined struct type to declare a struct pointer variable.
For example, declaring a pointer variable pointing to a student structure:
struct Student *ptr;
- Dynamically allocate memory: Assign memory space for a struct pointer variable.
For example, dynamically allocate memory using the malloc function.
ptr = (struct Student*)malloc(sizeof(struct Student));
- Using a struct pointer: accessing and modifying the fields of a struct using pointer variables.
For example, accessing and modifying fields in a student structure.
strcpy(ptr->name, "Tom");
ptr->age = 18;
ptr->score = 89.5;
- Freeing memory: After using a structure pointer, memory space needs to be released.
For example, releasing memory using the free function:
free(ptr);
The complete example code is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
char name[50];
int age;
float score;
};
int main() {
struct Student *ptr;
ptr = (struct Student*)malloc(sizeof(struct Student));
if (ptr == NULL) {
printf("Memory allocation failed.\n");
return -1;
}
strcpy(ptr->name, "Tom");
ptr->age = 18;
ptr->score = 89.5;
printf("Name: %s\n", ptr->name);
printf("Age: %d\n", ptr->age);
printf("Score: %.2f\n", ptr->score);
free(ptr);
return 0;
}
Output:
Name: Tom
Age: 18
Score: 89.50