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: Tom Age: 18 Score: 89.50