Find length of array in C
In contrast to several other programming languages, C does not include a built-in function that may be used to calculate the length of an array directly. However, you may get an array's length by dividing the overall size by the sizes of each component.
Program:
#include <stdio.h>
int main() {
int myArray[] = {1, 2, 3, 4, 5}; // Example array
// Calculate the total size of the array in bytes
int totalSize = sizeof(myArray);
// Calculate the size of an individual element in bytes
int elementSize = sizeof(myArray[0]);
// Calculate the length of the array by dividing total size by element size
int length = totalSize / elementSize;
printf("Array elements: ");
for (int i = 0; i < length; i++) {
printf("%d ", myArray[i]);
}
printf("\nLength of the array: %d\n", length);
return 0;
}
Output:
![Find length of array in C](https://static.tutorialandexample.com/c/find-length-of-array-in-c1.png)
Explanation:
- Using #include, we include the default input/output library.
- MyArray, an integer array, is declared and given some sample values.
- To get the overall size of the whole array in bytes, we utilize the sizeof() operator.
- To get the dimension in bytes of one array element (myArray[0]), we may also use sizeof().
- By dividing the overall size by the size of each member, we can get the array's length.
- To display the determined length, we use printf().
This approach is effective for arrays with a fixed size that are statically specified. The sizeof() strategy won't be effective if you deal with dynamic arrays allocated via pointers and operations like malloc() or similar ones. In such a case, you will need to handle the length independently.
Different methods used:
- By combining sizeof() and Division:
As was said previously, you may discover the array's overall size using the sizeof() operator, then split it by the amount of space of just one element to determine the length. For arrays that have been statically defined, use this method.
Program:
#include <stdio.h>
int main() {
int myArray[] = {1, 2, 3, 4, 5}; // Example array
// Calculate the length of the array using sizeof and division
int totalSize = sizeof(myArray);
int elementSize = sizeof(myArray[0]);
int length = totalSize / elementSize;
printf("Array elements: ");
for (int i = 0; i < length; i++) {
printf("%d ", myArray[i]);
}
printf("\nLength of the array: %d\n", length);
return 0;
}
Output:
![Find length of array in C](https://static.tutorialandexample.com/c/find-length-of-array-in-c2.png)
- How to Use a Sentinel Value
You can loop through the array until you reach a specified value that signifies the data's conclusion (a sentinel value). This technique is frequently applied to character arrays (strings), in which the null-terminating character ('0') indicates the string's end.
Program:
#include <stdio.h>
int main() {
char myString[] = "Hello, World!"; // Example string
int length = 0;
while (myString[length] != '\0') {
length++;
}
printf("String: %s\n", myString);
printf("Length of the string: %d\n", length);
return 0;
}
Output:
![Find length of array in C](https://static.tutorialandexample.com/c/find-length-of-array-in-c3.png)
- Employing a Macro:
You may create a macro that uses the sizeof operator to determine an array's length. Finding the length may be made easier by doing this.
Program:
#include <stdio.h>
#define ARRAY_LENGTH(arr) (sizeof(arr) / sizeof(arr[0]))
int main() {
int myArray[] = {1, 2, 3, 4, 5}; // Example array
int length = ARRAY_LENGTH(myArray);
printf("Array elements: ");
for (int i = 0; i < length; i++) {
printf("%d ", myArray[i]);
}
printf("\nLength of the array: %d\n", length);
return 0;
}
Output:
![Find length of array in C](https://static.tutorialandexample.com/c/find-length-of-array-in-c4.png)
- Keeping Length Apart:
If you're using randomly allocated arrays, you'll have to manage length on your own. The length can be kept distinct and updated each time an element is added or removed from the array.
Program:
#include <stdio.h>
#include <stdlib.h> // For dynamic memory allocation
int main() {
int initialSize = 5; // Initial size of the dynamic array
int* dynamicArray = (int*)malloc(sizeof(int) * initialSize); // Example dynamic array
// Populate the dynamic array with values
for (int i = 0; i < initialSize; i++) {
dynamicArray[i] = i + 1;
}
int length = initialSize; // Store the length separately
printf("Array elements: ");
for (int i = 0; i < length; i++) {
printf("%d ", dynamicArray[i]);
}
printf("\nLength of the array: %d\n", length);
// Free the dynamically allocated memory
free(dynamicArray);
return 0;
}
Output:
![Find length of array in C](https://static.tutorialandexample.com/c/find-length-of-array-in-c5.png)
- Pointer arithmetic use
You may employ pointer arithmetic to determine the length between the beginning and end of the array if you have a pointer to it and want to know how long it is. Both statically allocated arrays and dynamically created arrays can use this.
Program:
#include <stdio.h>
int main() {
int myArray[] = {1, 2, 3, 4, 5}; // Example array
int* endPointer = myArray + sizeof(myArray) / sizeof(myArray[0]);
int length = endPointer - myArray;
printf("Array elements: ");
for (int i = 0; i < length; i++) {
printf("%d ", myArray[i]);
}
printf("\nLength of the array: %d\n", length);
return 0;
}
Output:
![Find length of array in C](https://static.tutorialandexample.com/c/find-length-of-array-in-c6.png)
Time complexity:
- By combining sizeof and Division:
Using this approach, finding the dimension of an array has a constant time (O(1)) time complexity. The length is obtained by dividing the value of the sizeof operator by the dimension of a single element. The sizeof operation gives the size of the whole array in bytes. Since this computation is performed at compilation time, the array's size has no bearing on it.
- How to Use a Sentinel Value
When determining the dimension of an array with a sentinel value, the time complexity is linear (O(n)), where n is the total amount of array items. It is necessary to identify the flag value that indicates the end of the array by iterating through the full array.
- Employing a Macro:
Similar to the first technique, using a macro with sizeof then division to get an array's length has constant time (O(1)) time complexity. The macro's computation happens during compilation.
- Keeping Length Apart:
Finding an array's length by storing each element individually has a constant time (O(1)) time complexity. You may immediately retrieve the stored length, regardless of the size of the array.
- Pointer arithmetic use
When using pointer arithmetic to determine an array's length, the time complexity is constant (O(1)). A straightforward process independent of the array's size is the arithmetic used to determine the distinction between the end pointer and the beginning pointer.ral complexity, making it the least efficient, especially for bigger arrays.