0

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..

2
  • What's the purpose of variable currNumOfElements then? Commented Apr 24, 2022 at 20:32
  • 2
    If your array is updated from an external source, then you must ensure that this external source updates currNumOfElements too, or that it provides some other mechanism to determine whether it changed the number of valid elements. Commented Apr 24, 2022 at 20:43

2 Answers 2

1

You can use your variable currNumOfElements to determine how many elements are in the array. Because it's a 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'.

Sign up to request clarification or add additional context in comments.

2 Comments

check the edit, my bad
I checked your edit, and my answer should still suffice. Good luck!
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.