Adventure Game Studio

AGS Support => Beginners' Technical Questions => Topic started by: Pax Animo on Fri 09/09/2022 23:50:09

Title: Array index length
Post by: Pax Animo on Fri 09/09/2022 23:50:09
Heya,

Is there a way to get the length of an array (structured array) rather than hardcoding the number, so for example i have:

Code (ags) Select
function population()
{
  for (int i = 0; i < 10; i++) {  //"instead of < 10 i'd like to just get the index length"
    countries[i].population += countries[i].birth_rate;
  }
}


If I initially set the array to 10 but decide to change it later how do i check the new index length?

Thanks for any help
Title: Re: Array index length
Post by: eri0o on Sat 10/09/2022 01:15:29
What do you mean structured array?

If you are thinking of something like countries.Length, then it's implemented in ags4 with the new compiler but not possible in ags3. I recommend using something like below for now

Code (ags) Select
#define COUNTRIES_MAX 10
Country countries[COUNTRIES_MAX];

// ... later

function population()
{
  for (int i = 0; i < COUNTRIES_MAX; i++) {  //"instead of < 10 i'd like to just get the index length"
    countries[i].population += countries[i].birth_rate;
  }
}
Title: Re: Array index length
Post by: Crimson Wizard on Sat 10/09/2022 10:10:03
For dynamic arrays you'd have to store the length in the variable, so you'd have
Code (ags) Select

int num_countries;
Country countries[];



Alternatively, there's a trick where you store the array length in the first element. This will make it possible to pass dynamic array to another function or return from function, without having to pass its length in a separate variable. The downside is that you have to remember that the first element is not a real item, so don't assign anything meaningful to it and skip it whenever you loop through array.
Title: Re: Array index length
Post by: Snarky on Sat 10/09/2022 10:52:05
Quote from: Crimson Wizard on Sat 10/09/2022 10:10:03
Alternatively, there's a trick where you store the array length in the first element. This will make it possible to pass dynamic array to another function or return from function, without having to pass its length in a separate variable. The downside is that you have to remember that the first element is not a real item, so don't assign anything meaningful to it and skip it whenever you loop through array.

Or in some cases you can adopt the null-terminated convention, where you add a blank entry as the last element as a signal that you've reached the end. This works well for arrays of strings or pointers. The drawback is that you can't tell how big the array is without looping through it, and of course that you can't have any null elements in the array.