構造体ポインターのC言語における定義と使用法
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