How to get the length of a variable size array of structs?

503 Views Asked by At

I'm breaking my head trying to sort out this problem, and I have not been able to sort it out. Given I have a struct:

struct person
{
     String name,
     String city,
     int age
}

I am reading a list of people from a certain file provided externally, and populating an array of this struct. This is done via a function, lets say

person * readFromFile(filename);

This function has the logic to read the file, create a variable size array of structs (adapted to the number of persons in the file), and return said array.

However, when I try to assign that outcome to a pointer, I'm not getting the elements of the array:

...
person * myPeople;
myPeople = readFromFile("/people.txt");
int n= ;// different things I-ve tried here
Serial.println("n is" + n);
for(int i=0; i<n; i++)
{ 
     Serial.println(myPeople.name + " (" + String(myPeople.age) + "), "+myPeople.city
}

I've tried several things to get the number of elements once the array is populated after researching how to do it, to know:

int n = sizeof(myPeople)/sizeof(myPeople[0]);
int n = sizeof myPeople / sizeof *myPeople;
int n = sizeof(myPeople) / sizeof(person);
int n = (&myPeople)[1] - myPeople;

But to no avail: I have 5 elements in the file, but n does never show the expected value (and of course the for loop breaks).

Can I get some assistance? what am I be doing wrong?

Thanks

1

There are 1 best solutions below

2
On BEST ANSWER

Instead of using "String" (Whatever that is in your case.), use a fixed array of char for each string.

Like so:

struct person
{
     char name[32], /* string name has a length of 31 + 1 for NULL-termination */
     char city[32], /* string city has a length of 31 + 1 for NULL-termination */
     int age
}