Home  >  Article  >  Backend Development  >  How to get the length of an array in C language

How to get the length of an array in C language

小老鼠
小老鼠Original
2024-05-08 17:45:28909browse

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]));

How to get the length of an array in C language

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:

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

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int length = sizeof(arr) / sizeof(arr[0]);
    printf("数组长度: %d\n", length);

    return 0;
}</code>

In this example, arr is 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:

<code class="c">#define ARRAY_LENGTH(arr) (sizeof(arr) / sizeof(arr[0]))</code>

Now, we can use macro to get the array length:

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

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int length = ARRAY_LENGTH(arr);
    printf("数组长度: %d\n", length);

    return 0;
}</code>

Note:

  • These methods only apply to A static array of known length.
  • If the length of the array is variable (for example, a dynamically allocated array), you need to use other methods to track the length of the array.

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!

Statement:
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