简体   繁体   中英

allocating and populating a large array

I want to allocate and initialize a very large array of unsigned long ints. The array is a simple 1-D array, and I want to populate it with the value of the first N primes. I already have a program that will spit these out into a .cpp file for inclusion. I'm just not sure of the syntax to initialize the array. I know that

unsigned long int *known = new unsigned long int[N];

will create the array on the heap, but I'm not sure how to initialize the members.

You basically just loop over the array and assign the correct value to every element, like so:

for(size_t idx = 0; idx < N; ++idx)
{
  *(known + idx) = retrieve_value(idx);
}

Obviously with the retrieve_value function returning the appropriate value that needs to be assigned to known[idx].

You can also make use of the pointer/array equivalence and write the code using array syntax:

for(size_t idx = 0; idx < N; ++idx)
{
  known[idx] = retrieve_value(idx);
}

That said, unless there is a good reason for new'ing the array this way I would strongly recommend using one of the standard containers like std::vector or std::array in this case as it'll avoid the memory management headaches that are mostly unnecessary these days. If N is known at compile time, std::array is likely to have less overhead, otherwise using std::vector with an appropriate reserve() call should do the job fine, too. I would really only suggest dealing with raw memory if you absolutely have to squeeze the last byte out of the available memory.

I would suggest you to create an array initializer class which will accept a pointer to array and number of elements to be created. Use a global variable of this class. Upon creation the constructor will populate the array.

    class ArrayInitializer{
       ArrayInitializer(unsigned long* ptr, size_t Size);
       ...
       ...
    };

Now create a global variable

    //include your header here,
    ArrayInitializer g_arrayInit(known,N);

Global variables are created as soon as program execution begins. Also you can you this class to clean up the memory allocated using 'new'

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