0

I have a struct array :

struct Stu* arr = (struct Stu*)calloc(ogr,sizeof(struct Stu));

And I have a void function it gets arr as a paramater and i have to find the len of arr in function.

struct Lsn {
    char lsn_name[50];
}; 
struct Stu {
    char name[40];
    char surname[20];
    char st_id[11];
    struct Lsn* lsn;
};
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41

2 Answers2

1

There is no way in C to determine the length (size) of an array that is passed as pointer. You must pass the size as a parameter to the function:

void f(void *arr, size_t size);

If, for one or another reason, that is not possible, and if the array is passed empty, then you could do a hack by setting the first bytes of the array to the length, for example:

struct Stu* arr = (struct Stu*)calloc(ogr,sizeof(struct Stu));
*((int *)arr)= ogr;

and in the function:

size= *((int *)arr);   // get the size
*((int *) arr)= 0;     // reset the first few bytes
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
  • struct Lsn { char lsn_name[50]; }; struct Stu { char name[40]; char surname[20]; char st_id[11]; struct Lsn* lsn; }; this is my struct. I have to print all lsn object but i send Stu object to function – RavenHunter Dec 26 '19 at 13:52
0

C doesn't have a default way to know the size of array like you want, but you can implement it in the same way a string length is passed down.

In string the character '\0' gives the strin end, so when you calculate the length the function counts the characters till it meets a '\0' character. If memory isn't the problem for you make one extra struct(allocate one extra struct memory). then inside that struct keep something unique so you'll know it denotes the end. You can then check that value inside the function.

Atreyagaurav
  • 1,145
  • 6
  • 15