I have an array of sruct sockaddr_in
:
struct sockaddr_in saddrlist[MAX] = {0};
the array is also being updated from external sources with memcpy, so thats the point where i dont know anymore about the count. and currNumOfelements.
Now at some point, i want to check how many elements are in the array. What I tried:
printf("before: %d",getsize(saddrlist));
memcpy(&myotherlist, saddrlist, sizeof(saddrlist) * MAX);
printf("after: %d",getsize(saddrlist));
Which results in:
before: 52448
after: 52448
int getsize(struct sockaddr_in saddrlist[10])
{
uint8_t numOfElements = 0;
for (size_t i = 0; i < MAX; i )
if (saddrlist[i] != 0)
numOfElements ;
}
This obviously doesn't work because if (saddrlist[i] != 0)
is an invalid comparison.. but how do i do it then? I get so confused using c
..
CodePudding user response:
You can use your variable currNumOfElements
to determine how many elements are in the array. Because it's static array, saddrlist
will always have MAX
elements in it. You get to decide what's a 'valid' configuration for your struct, and what's 'invalid'.
CodePudding user response:
You could try to memcmp
the addresses to a zero initialized one:
int getsize(struct sockaddr_in *saddrlist)
{
int numOfElements = 0;
struct sockaddr_in zero = { 0 }; // declare a local "null" sockaddr_in
for (size_t i = 0; i < MAX; i ) {
if (memcmp(saddrlist i, &zero, sizeof(zero)) != 0)
numOfElements ;
else break; // stop at first "null" address
}
return numOfElements;
}