How to Find Size of Array in C: Simple Syntax and Example
In C, you can find the size of an array by using the
sizeof operator. Calculate the total size of the array in bytes with sizeof(array) and divide it by the size of one element with sizeof(array[0]) to get the number of elements.Syntax
To find the number of elements in an array, use this formula:
sizeof(array): gives total size in bytes of the whole array.sizeof(array[0]): gives size in bytes of one element.- Divide total size by element size to get the count of elements.
c
size_t array_size = sizeof(array) / sizeof(array[0]);Example
This example shows how to find and print the number of elements in an integer array.
c
#include <stdio.h> int main() { int numbers[] = {10, 20, 30, 40, 50}; size_t size = sizeof(numbers) / sizeof(numbers[0]); printf("The array has %zu elements.\n", size); return 0; }
Output
The array has 5 elements.
Common Pitfalls
Common mistakes when finding array size in C include:
- Using
sizeofon a pointer instead of the actual array, which gives the pointer size, not the array size. - Trying to find size of dynamically allocated arrays with
sizeof, which does not work. - Calculating size inside functions where the array decays to a pointer.
Always use sizeof on the array variable in the same scope where it is declared.
c
#include <stdio.h> void printSize(int *arr) { // Wrong: sizeof(arr) returns size of pointer, not array size_t size = sizeof(arr) / sizeof(arr[0]); printf("Inside function, size is %zu (incorrect)\n", size); } int main() { int arr[] = {1, 2, 3, 4}; size_t size = sizeof(arr) / sizeof(arr[0]); printf("In main, size is %zu (correct)\n", size); printSize(arr); return 0; }
Output
In main, size is 4 (correct)
Inside function, size is 2 (incorrect)
Quick Reference
Remember these tips when finding array size in C:
- Use
sizeof(array) / sizeof(array[0])to get element count. - Works only for arrays, not pointers.
- Use in the same scope where array is declared.
- For dynamic arrays, track size manually.
Key Takeaways
Use sizeof(array) divided by sizeof(array[0]) to find the number of elements in a C array.
Do not use sizeof on pointers to find array size; it returns pointer size, not array length.
Calculate array size in the same scope where the array is declared.
For dynamic arrays, sizeof cannot determine size; track length manually.
Always use size_t type for array size to avoid signed/unsigned issues.