NULL - ヌルポインタ定数
NULLはヌルポインタ定数と呼ばれ「整数の0」または「(void*)にキャストした整数の0」として「stddef.h」で定義されています。
ポインタにNULLを代入したものはヌルポインタと呼ばれます。NULLはあらゆるポインタ型に代入できます。
// ヌルポインタ void* ptr = NULL; int32_t* int32_ptr = NULL; float* float_ptr = NULL;
NULLのサンプル
NULLのサンプルです。
メモリ割り当てのチェック
以下のサンプルでは、calloc関数のメモリ割り当てに失敗した場合はNULLが返されます。ですので、メモリが割り当てられていることのチェックに利用できます。
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
// ポインタ
int32_t* nums = calloc(sizeof(int32_t), 10);
// ポインタがNULLではない
if (nums != NULL) {
printf("Success\n");
}
else {
printf("Fail\n");
}
free(nums);
}
出力結果
Success
木のノードで子要素が存在するか
木のノードで、子要素が存在するかどうかのチェックのサンプルです。
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
struct myapp_node {
struct myapp_node* first_child;
struct myapp_node* last_child;
};
int main(void) {
// 親ノード
struct myapp_node* parent = calloc(sizeof(struct myapp_node), 1);
// 子ノード
struct myapp_node* first_child = calloc(sizeof(struct myapp_node), 1);
// 親ノードの最初の子に代入
parent->first_child = first_child;
if (parent->first_child != NULL) {
printf("Have First Child\n");
}
if (parent->last_child == NULL) {
printf("Don't Have Last Child\n");
}
free(parent);
free(first_child);
}
出力結果
Have First Child
C言語ゼミ


