1

I want to have a linked list, with a variable which has dynamic size, because I want to just allocate different sizes for a variable in different nodes.
for example node1 has a array variable with size 1, but node 2 has a array variable with size 10, and node3 never allocates this array. like this:

struct st{
   int * var_dynamic;
   int x;
};

now I want to initialize them. for the static one, it is like this:

struct st st1;
st1.x=1;

but how can I initialize the dynamic one?
Is it something like this?

st1.var_dynamic= new int [100];

and if yes, Is this way correct and efficient?

Fattaneh Talebi
  • 727
  • 1
  • 16
  • 42

1 Answers1

2

The most idiomatic, straightforward, and safe solution is to simply use std::vector:

struct st
{
  std::vector<int> var_dynamic;
  int x;
};

For using std::vector, consult a reference documentation, or your favourite book.

Community
  • 1
  • 1
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • @FattanehTalebi I suggest you first consult the docs I linked to, or pick up an introductory/reference book from those I linked to. Then, if there's still stomething unclear, search SO and the Internet, and if it's still unclear, ask another question. – Angew is no longer proud of SO Jan 08 '16 at 15:53