In C: How do you find the number of elements in an array of structs, after sending it to a function?
int main(void) {
myStruct array[] = { struct1, struct2, struct3, struct4, struct5, struct6 };
printf("%d\n", sizeof(array));
printf("%d\n", sizeof(array[0]));
f(array);
}
void f(myStruct* array) {
printf("%d\n", sizeof(array));
printf("%d\n", sizeof(array[0]));
}
For some reason the printf in main shows different results than the printf in f. My need is to know how many elements are in the array.
Array in C can be defined as a method of clubbing multiple entities of similar type into a larger group. These entities or elements can be of int, float, char, or double data type or can be of user-defined data types too like structures.
Use the len() method to return the length of an array (the number of elements in an array).
You can't.
You have to pass the size to the function, eg:
void f(myStruct* array, size_t siz);
Also notice that in f
array is a pointer, while in main
it is an array. Arrays and pointers are different things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With