In C, you cannot directly determine the size of an array using a built-in function once the array has been passed to a function or lost its original context. However, you can calculate the size of a statically allocated array using the sizeof
operator. For dynamically allocated arrays, you need to keep track of their size separately.
Here's an example of how to determine the size of a statically allocated array:
c
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]);
printf("Size of the array: %d\n", size);
return 0;
}
In this example, the sizeof(numbers)
returns the total size of the array in bytes, and sizeof(numbers[0])
returns the size of a single element in bytes. Dividing the total size by the size of a single element gives you the number of elements in the array.
Keep in mind that this method works only for statically allocated arrays. For dynamically allocated arrays, you need to track the size manually using a variable or a data structure.
Comments
Post a Comment