What is the method in C language to determine if an arr…

In C language, there are two ways to determine if an array is empty.

  1. Check if the length of the array is 0: By determining if the length of the array is 0, you can verify if the array is empty. For example:
int arr[10];

if (sizeof(arr) / sizeof(arr[0]) == 0) {
    printf("数组为空\n");
} else {
    printf("数组不为空\n");
}
  1. Check if the address of the first element in the array is NULL: By checking if the address of the first element in the array is NULL, we can determine if the array is empty. For example:
int arr[10];

if (arr == NULL) {
    printf("数组为空\n");
} else {
    printf("数组不为空\n");
}

It is important to note that the above methods can only determine if a static array is empty. For dynamic arrays (arrays allocated through malloc or calloc functions), these methods cannot be used for determining emptiness. For dynamic arrays, pointers can be used to check if they are empty. For example:

int *arr = malloc(sizeof(int) * 10);

if (arr == NULL) {
    printf("数组为空\n");
} else {
    printf("数组不为空\n");
}
bannerAds