I have a small program computing the forces of planets on each other. My program has two arrays of structs, one that holds the positions and velocities before iterations, and the other holds what their positions and velocities will be after the iterations.
At the end of each iteration, I’d like to move the values from the second array into the first and the second array can become garbage (but needs to point to some valid memory location I can write to later). I thought I could simply switch the arrays since an array is a pointer, but the compiler won’t let me.
Consider this example:
typedef struct { int a; } Foo;
int main()
{
Foo bar[8], baz[8];
Foo *temp = baz;
baz = bar; //ISO C++ forbids the assignment of arrays
bar = temp; //incompatible types in assignment of Foo* to Foo[8]
}
This is what I’d like to do. It would certainly be faster than a for loop from 1 to N.
You should consider using
std::vectorwhich can be swapped in constant time:Or if you don’t want to do that and instead want to manually manage your memory, you can use
new[]to get a pointer to an array on the free store and swap the pointers when you want to swap the arrays.If you must have your arrays on the stack, the only way to do this without actually swapping each element would be to create the arrays on the stack and instead of using the arrays, use pointers to the arrays: