Home > Backend Development > C#.Net Tutorial > How to find the length of an array in C language

How to find the length of an array in C language

小老鼠
Release: 2024-05-08 17:42:15
Original
456 people have browsed it

The array length can be obtained through the sizeof operator. The formula is: sizeof (array name) / sizeof (array element type). The result is the array length.

How to find the length of an array in C language

How to find the length of C language array

Direct method

<code class="c">#include <stdio.h>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int len = sizeof(arr) / sizeof(arr[0]);
    printf("数组长度:%d\n", len);
    return 0;
}</code>
Copy after login

sizeof operator

In C language, the sizeof operator can obtain the size of a variable or data type. For arrays, sizeof returns the total number of bytes occupied by all elements in the array. The array length is obtained by dividing this by the size of the individual elements.

Other methods

The above method is the standard method, but in some cases, other methods can also be used to find the array length:

  • Array Boundary Macros: Some compilers provide array boundary macros, such as _countof (Visual C) or __builtin_object_size (GCC). These macros directly return the array length.
  • Pointer to the end of the array: When allocating memory for an array, the system will allocate additional space to store the end of the array. There is a pointer before the end of the array pointing to the first element of the array. By subtracting the values ​​of these two pointers, the array length can be obtained.

The above is the detailed content of How to find the length of an array in C language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template