【C言語】stdlib.hを使ってメモリ管理、数値変換、乱数生成、プログラムの終了処理などを行う【標準ライブラリ】
stdlib.hとは?
stdlib.h
はC言語の標準ライブラリの一つであり、メモリ管理、数値変換、乱数生成、プログラムの終了処理など、汎用的な機能を提供するヘッダーファイルです。
このライブラリには、プログラムをより柔軟に制御するための多くの便利な関数が含まれています。
メモリ管理関数
動的メモリを確保・解放するための関数として、以下のものがあります:
malloc
:指定したバイト数のメモリを確保calloc
:ゼロ初期化されたメモリを確保realloc
:確保済みのメモリサイズを変更free
:確保したメモリを解放
使用例
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int*)malloc(5 * sizeof(int)); // 5個のintを確保
if (arr == NULL) {
printf("メモリ確保失敗\n");
return 1;
}
for (int i = 0; i < 5; i++) {
arr[i] = i * 2;
}
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
free(arr); // メモリ解放
return 0;
}
乱数の生成
乱数を生成するには、rand()
と srand()
を使用します。
使用例
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL)); // 乱数の種を設定
for (int i = 0; i < 5; i++) {
printf("%d\n", rand() % 100); // 0~99の乱数を生成
}
return 0;
}
文字列と数値の変換
文字列を数値に変換する関数として、以下のものがあります:
atoi
:文字列を整数に変換atof
:文字列を浮動小数点数に変換strtol
:文字列を長整数に変換
使用例
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "12345";
int num = atoi(str); // 文字列を整数に変換
printf("変換結果: %d\n", num);
return 0;
}
配列のソート(qsort)
qsort
を使用すると、任意の配列を簡単にソートできます。
使用例
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int main() {
int arr[] = {32, 5, 1, 99, 16};
int size = sizeof(arr) / sizeof(arr[0]);
qsort(arr, size, sizeof(int), compare);
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
プログラムの終了処理
プログラムを終了するには exit()
を使用します。
使用例
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("プログラムを終了します。\n");
exit(0); // 正常終了
}
system関数によるコマンド実行
system()
を使うと、外部コマンドを実行できます。
使用例
#include <stdio.h>
#include <stdlib.h>
int main() {
system("dir"); // Windowsならディレクトリ一覧を表示
return 0;
}