Dynamically allocating structure array

structure *test = new structure[2];

or

structure *test[2] = {new structure, new structure};

Curious, which one of these do you guys think are actually better. I mean I'm not talking about speed. Obviously it would be very similar if not the same. I'm just saying for coding practice. I have this array of 2 structures I need to create. Usually accessing things dynamically allocated you use the -> operator but with option 1 you use the . operator. Obviously its just syntax for the compiler and the executable would be the same. I'm just wondering which is better.
Last edited on
Those two snippets do a different thing: in first case you have a pointer to first element of unnamed dynamically allocated array of two elements. In second case you ahve a named aray of two pointers (which you initialize in init list).

Both of those are viable and can be used for different things, so there is no way to say which one is "better"
In addition to what MiiNiPaa says:

The second is slower since it does two memory allocations instead of 1. Not a big deal here but if you allocated 10,000 it would make a difference.

When the time comes, you can delete the first with delete[] test, but to delete the second you have to iterate through the array.

The first array will last until it's deleted. In the second case, the values in the array will last, but the array itself will be destroyed when it goes out of scope.
Topic archived. No new replies allowed.