简体   繁体   中英

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, 

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

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]
}

No. That's one reason everybody uses containers. If std::vector doesn't please you, you can make a container of your own.

Edit: Since dynamic array size is determined at runtime, someone must store the size somewhere (unless you're willing to use a sentry value). Not even the compiler can help, because the size is determined in runtime.

If you want to store the size your dynamic array inside it, well, just do so :

#include <iostream>
#include <cstdint>
#include <cstddef>
using std::size_t;

struct head_t { size_t size; int data[]; };

int main() {
    head_t* h = static_cast<head_t*>(::operator new(sizeof(head_t) + 10 * sizeof(int)));
    h->size = 10;
    int* my_10_ints = h->data;
    // Oh noez! I forgot 10!
    size_t what_was_10_again = static_cast<head_t*>(static_cast<void*>(my_10_ints) - offsetof(head_t, data))->size;
    ::std::cout << what_was_10_again << "\n";
    ::operator delete(static_cast<void*>(my_10_ints) - offsetof(head_t, data));
}

You can even put that functionality in a libraryesque set of functions! Oh, and once you do that you realize you could just have an unordered_map that maps pointers to sizes. But that would be like using vector : Totally boring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM