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
struct personArray { struct person *data; int totalelements; int nelements; };... every time yourealloc()data (whennelements == totalelementsand you need more space) adjusttotalelements, everytime you add a person adjustnelements.person * readFromFile(filename, &nReadPersons), where the latter is an out-argument, populated by your function and specifies the number of items in the returned sequence. All that's left it to actually write it now. Personally I prefer doing what @pmg suggests. it keeps codependent data together, nice and tidy.