UPDATE : Answer at the bottom.
Hi Guys,
How to initialize an 'array of pointers to a struct' ? The catch is, the array is a member variable and the size passed to the declaration of the array in the constructor is variable entity.
typedef struct Node {
string key;
int value;
struct Node * left;
struct Node * right;
}doubly;
class myHashStrKey{
private:
size_t hashsize;
doubly * table[];
public:
myHashStrKey(){
hashsize = ((size_t)-1);
doubly * table[hashsize];
memset(table,NULL,hashsize);// This is giving segmentation fault
}
};
//Called constructor; myHashStrKey sss = myHashStrKey();
Here I want the table to be a array of pointers to the Doubly nodes and I want all the pointers to be initialized to NULL . Whats wrong with this code here ? What other better way are there to perform the above ? Thanks in advance.
UPDATE :
After the discussion, considering the size is big let down I have modified the code . But how to fill vector table with certain number of NULL values ?I tried the below code but it is not working .
<pre><code>
for(int i =0;i < hashsize;i++){
table.push_back((doubly *)NULL);
}
table.insert(table.begin(),hashsize,NULL);
//Both give invalid static_cast from type `int' to type `doubly*'
</code></pre>
ANSWER UPDATE :
myHashStrKey::table(myHashStrKey::hashsize, static_cast(0));
myHashStrKey::table(myHashStrKey::hashsize);
//Above 2 does not work
for(int i =0;i != myHashStrKey::hashsize;i++){ //lesser than symbol spoils the display
myHashStrKey::table.push_back((doubly *)NULL);
}
//Above works
myHashStrKey::table.insert(myHashStrKey::table.begin(),hashsize,((doubly *)NULL));
//This too works
Variable-length arrays are not supported by the C++ standard. Instead, simply use a std::vector
:
private:
std::vector<doubly *> table;
...
myHashStrKey()
: table(num_elements, NULL) // Initialises vector
{
...
}