Search code examples
c++dynamic-arrays

Size of dynamic array or loop through it without knowing size


Like in title, can I somehow get size of dynamic allocated array (I can't keep it separately), or somehow loop through this array without using it's size?

int *ar=new int[x]; //x-size of array, I don't know it in the beggining, 

P.S. If I wanted to use std::vector, I wouldn't ask about it, so don't tell me to use it :)


Solution

  • A std::vector is designed for this.

    If you can't use a std::vector I can see a couple of options.

    1) Use an array terminator.

    If your array should only contain positive numbers (for example) or numbers within a given range then you can use an illegal value (eg -1) as an array terminator.

    for(int* i = arr; *i != -1; ++i)
    {
        // do something with *i
    }
    

    2) Embed the length in the array.

    For a numeric array you could, by convention, store its length in the first element.

    for(int i = 0; i < arr[0]; ++i)
    {
        // do something with arr[i + 1]
    }