0
votes

I am trying to statically allocate memory to an array of pointers to a struct called "mini". The "mini" structs serve as a way to store an index and the data so I can do an indirect sort by sorting a pointer to the struct. When I declare the array, the array is allocated memory to store the pointers, but the pointers themselves are not allocated any memory for the "mini" structs. It is important that it is statically allocated because it is part of a sorting algorithm, so I am trying to avoid dynamic memory allocation.

This is the declaration of mini and an array of pointers to mini:

typedef struct {
    long long index;
    string data;
} mini;

static mini* ssn[1010000];

I can dynamically allocate as follows:

for (int j = 0; j < 1010000; j++){
    ssn[j] = new mini();
}

The problem arises when I try to statically allocate memory to each of the pointers. Here are a few things I have tried:

static mini* ssn[1010000] = {{0,""}};

static mini* ssn[1010000]  = {{new mini()}};

None of these compile successfully. Is there any way to statically allocate memory for each pointer in the array?

1
You don't declare a struct called mini but an instance of an anonymous struct called mini. It looks you're coming from c and confuse a number of things here.πάντα ῥεῖ
The first problem is that you don't use std::vector instead of plain and simple arrays. The second problem is why the hell do you want to allocate 1010000 elements immediately?Some programmer dude

1 Answers

0
votes

You have an array of pointers and you want to initialize the array (each pointer element) with a different value (allocation result). There is no way to do such initialization on declaration except to provide a value for each element:

static mini* ssn[4] = {new mini(), new mini(), new mini()};

Each element for which you haven't provided a value will be initialized with default value 0.

If you need a fixed-length array, it is better to use std::array. C++ have powerful type system, use it. In this case the initialization could be generalized:

struct Mini {
    int x;
};

template <class Ar, class F, size_t... I>
static auto init(F factory, std::index_sequence<I...>) noexcept {
    return Ar{factory(I)...};
}

using Array = std::array<Mini*, 20>;
static Array ssr(init<Array>([](...) { return new Mini(); }, std::make_index_sequence<20>()));

It is effectively the same:

static Array ssr(Array{new Mini(), new Mini(), ...})

The compiler will optimize the Array copy. Note, this solution requires c++14, although it could be adapted to c++11.