C语言结构体指针的定义和使用方法如下:
定义结构体类型:首先需要定义一个结构体类型,可以包含多个字段(成员变量)。例如,定义一个表示学生信息的结构体类型:
struct Student { char name[50]; int age; float score;};声明结构体指针变量:使用定义好的结构体类型,声明一个结构体指针变量。例如,声明一个指向学生结构体的指针变量:
struct Student *ptr;动态分配内存:为结构体指针变量分配内存空间。例如,使用malloc函数动态分配内存:
ptr = (struct Student*)malloc(sizeof(struct Student));使用结构体指针:通过指针变量来访问和修改结构体的字段。例如,访问和修改学生结构体的字段:
strcpy(ptr->name, "Tom");ptr->age = 18;ptr->score = 89.5;释放内存:使用完结构体指针后,需要释放内存空间。例如,使用free函数释放内存:
free(ptr);完整示例代码如下:
#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;}运行结果:
Name: TomAge: 18Score: 89.50 
