how to declare dynamic struct

#include <iostream>

using namespace std;

struct test
{
int a;
int b;
};

const int size = 10;

int main()
{
test *p = new test[size]; // ???? is it the way to declare dynamic struct.

...
...

return 0;
}

Guys please help me on the dynmaic struct in c++. I am using VS 2010.
If you mean that you want to create an array which's size you don't know at compile time, then it is the way.. or at least very close.

1.: Your size variable is a constant, therefore it can be used to create static arrays as well. For dynamic arrays, it could be a non-constant variable.
1
2
3
//Static arrays
const int size = 10;
test p[size];

2.: If you use new, or new[], always use a delete or delete[] as well (otherwise, you will get a memory leak), in your case :
1
2
3
test *p = new test[size];
//do stuff with p
delete[] p;

3.: I highly recommend using std::vector. You can declare it's size dynamically, AND you can easily change it's size dynamically as well. Also, you don't have to worry about new-ing and delete-ing, it is done automatically.
For more information : http://www.cplusplus.com/reference/stl/vector/
Topic archived. No new replies allowed.