How to get the length of an array in C language

小老鼠
Release: 2024-05-08 17:45:28
Original
853 people have browsed it

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:

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

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]))
Copy after login

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; }
Copy after login

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!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!