C Array Size
In this page:
Fixed Size at Declaration
An array's size is fixed at the moment it's declared, specified as a number inside square brackets, and unlike some other languages, a standard C array cannot grow or shrink after that.
Example: Fixed Size at Declaration
#include <stdio.h>
int main() {
int arr[5];
printf("%zu", sizeof(arr));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Finding an Array's Size with sizeof
The sizeof operator applied to an array returns the total number of bytes it occupies, and dividing that by the size of a single element, using sizeof(arr[0]), is the standard way to compute how many elements it holds.
Example: Finding an Array's Size with sizeof
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]);
printf("%d", length);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Array Size vs Number of Elements
An array's total byte size and its element count are related but different: total bytes equals the element count multiplied by the size of each individual element, which matters for types larger than one byte.
Example: Array Size vs Number of Elements
#include <stdio.h>
int main() {
double arr[4];
printf("Bytes: %zu, Elements: %zu", sizeof(arr), sizeof(arr) / sizeof(arr[0]));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Size of Arrays Passed to Functions
When an array is passed as a function parameter, it decays into a pointer, so sizeof inside that function reports the size of the pointer rather than the original array, requiring the element count to be passed in separately.
Example: Size of Arrays Passed to Functions
#include <stdio.h>
void showSize(int arr[]) {
printf("%zu", sizeof(arr));
}
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
showSize(numbers);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Sizing Arrays for Input
Arrays intended to hold user input or other variable amounts of data are still given a fixed maximum capacity, often defined with a named constant, and the program tracks separately how many of those slots are actually in use.
Example: Sizing Arrays for Input
#include <stdio.h>
#define MAX_SIZE 10
int main() {
int data[MAX_SIZE];
printf("%d", MAX_SIZE);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: