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
In f array
is a pointer, in main array
is an array.
In the code above, function f() has no way of knowing how many elements were in your original array. It's a feature of the language and there's no way around it. You'll have to pass the length.
When you use sizeof
in main
, it's evaluating the array, and gives the size of the actual array.
When you use sizeof
in f
, you've passed the name of the array as an argument to a function, so it has decayed to a pointer, so sizeof
tells you about the size of a pointer.
Generally speaking, if you pass an array to a function, you need to either write the function to only work with one specific size of array, or explicitly pass the size of array for it to work with on a particular invocation.
you have to end the array with a special value and in called function you have to count up to that value that is how strlen() works it counts up to NULL '\0' value.
As an example to your solution:
Given
struct contain {
char* a; //
int allowed; //
struct suit {
struct t {
char* option;
int count;
} t;
struct inner {
char* option;
int count;
} inner;
} suit;
};
// eg. initialized
struct contain structArrayToBeCheck[] = {
{
.a = "John",
.allowed = 1,
.suit = {
.t = {
.option = "ON",
.count = 7
},
.inner = {
.option = "OFF",
.count = 7
}
}
},
{
.a = "John",
.allowed = 1,
.suit = {
.t = {
.option = "ON",
.count = 7
},
.inner = {
.option = "OFF",
.count = 7
}
}
},
{
.a = "John",
.allowed = 1,
.suit = {
.t = {
.option = "ON",
.count = 7
},
.inner = {
.option = "OFF",
.count = 7
}
}
},
{
.a = "John",
.allowed = 1,
.suit = {
.t = {
.option = "ON",
.count = 7
},
.inner = {
.option = "OFF",
.count = 7
}
}
}
};
in main()
printf("Number of Struct within struct array: %d \n", sizeof(structArrayToBeCheck)/sizeof(struct contain));
gives you the correct answer.