Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I find the length of an array in C/C++?
To find the length of an array in C, we can use various approaches that are essential for array manipulation. Finding the length of an array is a fundamental task used in looping through arrays, sorting, searching, and memory management operations.
In this article, we will explore different methods to determine the size of an array in C programming.
Syntax
// Method 1: Using sizeof operator int length = sizeof(array) / sizeof(array[0]); // Method 2: Using pointer arithmetic int length = *(&array + 1) - array;
Method 1: Using sizeof() Operator
The sizeof() operator returns the total size in bytes. To get the array length, divide the total size by the size of one element −
#include <stdio.h>
int main() {
int arr[5] = {4, 1, 8, 2, 9};
int len = sizeof(arr) / sizeof(arr[0]);
printf("The length of the array is: %d\n", len);
return 0;
}
The length of the array is: 5
Method 2: Using Pointer Arithmetic
This approach uses pointer arithmetic to calculate array length −
- The
&arrgets the address of the entire array - Adding 1 moves the pointer to just past the array
- Subtracting the original array pointer gives the element count
#include <stdio.h>
int main() {
int arr[5] = {5, 8, 1, 3, 6};
int len = *(&arr + 1) - arr;
printf("The length of the array is: %d\n", len);
return 0;
}
The length of the array is: 5
Method 3: Using Function Parameter
When arrays are passed to functions, you must pass the size separately since sizeof() returns the pointer size −
#include <stdio.h>
void printArrayLength(int arr[], int size) {
printf("Array length in function: %d\n", size);
}
int main() {
int arr[6] = {1, 2, 3, 4, 5, 6};
int len = sizeof(arr) / sizeof(arr[0]);
printf("Original array length: %d\n", len);
printArrayLength(arr, len);
return 0;
}
Original array length: 6 Array length in function: 6
Comparison
| Method | Pros | Cons |
|---|---|---|
| sizeof() operator | Simple, compile-time calculation | Only works with arrays, not pointers |
| Pointer arithmetic | Works at compile-time | Complex syntax, array-only |
| Function parameter | Works with dynamic arrays | Requires manual size tracking |
Key Points
- The
sizeof()method only works with statically declared arrays, not with pointers or dynamically allocated arrays. - When an array is passed to a function, it decays to a pointer, losing size information.
- For dynamic arrays (malloc), you must manually track the size.
Conclusion
The sizeof() operator is the most common and reliable method for finding array length in C. However, remember that it only works with arrays declared in the same scope, not with function parameters or pointers.
