There are two ways to get the length of an array in C language: use sizeof() operator: length = sizeof(arr) / sizeof(arr[0]); use macro: #define ARRAY_LENGTH(arr) (sizeof( arr) / sizeof(arr[0]));

C language method to obtain the length of an array
In In C language, an array is a data structure that can store a collection of data of the same type. Unlike other programming languages, there is no built-in mechanism in C to get the length of an array. Therefore, we need to obtain the array length through other methods.
Method 1: Use the sizeof() operator
sizeof()The operator returns the bytes occupied by the variable or data structure in memory number. You can use it to calculate the array length as follows:
#include int main() { int arr[] = {1, 2, 3, 4, 5}; int length = sizeof(arr) / sizeof(arr[0]); printf("数组长度: %d\n", length); return 0; }
In this example,arris an array of integers.sizeof(arr)Returns the number of bytes occupied by the entire array,sizeof(arr[0])Returns the number of bytes occupied by a single array element. By dividing the former by the latter, we can get the length of the array.
Method 2: Using macros
We can define a macro to get the array length. Macros are preprocessor directives that are expanded at compile time. For example:
#define ARRAY_LENGTH(arr) (sizeof(arr) / sizeof(arr[0]))
Now, we can use macro to get the array length:
#include int main() { int arr[] = {1, 2, 3, 4, 5}; int length = ARRAY_LENGTH(arr); printf("数组长度: %d\n", length); return 0; }
Note:
The above is the detailed content of How to get the length of an array in C language. For more information, please follow other related articles on the PHP Chinese website!