Lester Crest
Lester Crest

Reputation: 21

How to find out the amount of elements in array created for a struct?

I created a certain struct and then I went on to create an array for the struct in the following manner:

struct members
{

char name[32];
intmax_t personalID;

}typedef struct members Member;

Member array_member[100];

Later on, I want to know how many elements there are in the array, according to some answers I have read, this should be enough

int nrofmembers = sizeof(array_member) / sizeof(array_member[0]);

But due to my experience, I know that this is not possible if the array itself is a parameter. So I tried this:

int nrofmembers =  sizeof(*array_member) / sizeof(array_member[0]);

Unfortunately, this has turned out to be wrong. The value of nrofmembers after this is 1, but that's not true.

Any advice on how to do this?

Upvotes: 0

Views: 50

Answers (1)

0___________
0___________

Reputation: 67516

If you have the pointer you cant use this simple compile time method. You need to pass the size of the array to the function

In C you always pass the pointer even if your declaration is ... foo(Member arr[]) or ... foo(Member arr[100])

struct members
{

char name[32];
intmax_t personalID;

}typedef struct members Member;

Member array_member[100];


int foo(Member *arr, size_t size)
{
    /* .... */
}

int main()
{
    /* correct */
    foo(array_member, sizeof(array_member) / sizeof(array_member[0]));
    printf("Hello World");

    return 0;
}

Upvotes: 1

Related Questions