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?

5
  • 2
    st1.array[1]=1; You didn't mention an array variable. Also, have you heard of std::vector? Commented Jan 8, 2016 at 14:28
  • 2
    Why not using a std::vector? It was designed to be efficient and error free. Commented Jan 8, 2016 at 14:28
  • 2
    Do you want to use a list in C++? If so, you'd just use std::list. Or you want an array? Then you want std::vector. Or do you want to implement a data structure yourself? Commented Jan 8, 2016 at 14:28
  • @NicolBolas yes your right, I correct it Commented Jan 8, 2016 at 14:31
  • @FrerichRaabe no I want to use it, thanks for suggestion. Commented Jan 8, 2016 at 14:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.