Home > Article > Backend Development > How to get the length of c array
In C language, the length of an array cannot be obtained directly, but there are the following methods to obtain it indirectly: use the sizeof operator to divide the size of a single element; use the #define preprocessor macro to define the length of the array; use a pointer Arithmetic calculation of array length; use dynamic array library functions (such as array_size()).
How to get the length of a C array
In C language, an array is a contiguous memory block in which Elements of the same type. The size of the array is determined at compile time, so its length cannot be obtained directly from the array itself. But there are the following methods to indirectly obtain the length of the array:
1. Use the sizeof operator
sizeof
operator to return the memory required for the array type The size, in bytes. To get the number of elements of an array, you can apply the sizeof
operator to an array type and divide it by the size of a single element:
<code class="c">int main() { int arr[] = {1, 2, 3, 4, 5}; int length = sizeof(arr) / sizeof(arr[0]); printf("数组长度:%d\n", length); return 0; }</code>
2. Using preprocessor macros
Preprocessor macros allow you to define a symbol that can be replaced by a value at compile time. You can use the #define
preprocessor directive to define a macro that contains the length of the array:
<code class="c">#define ARRAY_LENGTH 5 int main() { int arr[] = {1, 2, 3, 4, 5}; printf("数组长度:%d\n", ARRAY_LENGTH); return 0; }</code>
3. Using pointer arithmetic
The array name is essentially a pointer to the first element of the array. Therefore, you can use pointer arithmetic to calculate the length of an array. Specifically, you can point the array pointer to the last element, then subtract the pointer to the first element, and divide by the size of the element:
<code class="c">int main() { int arr[] = {1, 2, 3, 4, 5}; int *end = &arr[sizeof(arr) / sizeof(arr[0]) - 1]; int length = end - arr + 1; printf("数组长度:%d\n", length); return 0; }</code>
4. Using dynamic array library functions
Some C language libraries provide dynamic array library functions that allow you to create and manage dynamic arrays. These functions usually include a function that gets the length of the array, such as array_size()
Function:
<code class="c">#include <array.h> int main() { int arr[] = {1, 2, 3, 4, 5}; int length = array_size(arr); printf("数组长度:%d\n", length); return 0; }</code>
The above is the detailed content of How to get the length of c array. For more information, please follow other related articles on the PHP Chinese website!