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