Array index length

Started by Pax Animo, Fri 09/09/2022 23:50:09

Previous topic - Next topic

Pax Animo

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
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
Misunderstood

eri0o

#1
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
#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;
  }
}

Crimson Wizard

For dynamic arrays you'd have to store the length in the variable, so you'd have
Code: ags

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.

Snarky

#3
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.

SMF spam blocked by CleanTalk