Can I add my 2 cents worth? The other respondents are vastly more experienced & knowledgeable than I, but I am hoping this may be helpful in some way.
Can we see your updated code now that you are using vectors?
In an overall sense, it seems that you have found some C functions that do what you want, but surely there are C++ libraries out there that do the same thing. Using C functions seems to have led to the whole program to be written in C. The program might be somewhat simpler/easier if it was written in C++.
I am wondering if you are aware of the differences between C and C++ ? IMO the two are rather different animals. C++ has the Standard Template Library (STL), this basically means there are containers like std::vector, classes and algorithms that operate on them, plus things like range based for loop, which means one can avoid all these problems with arrays. Range based for loops are very useful for iterating through an entire container easily.
JamieAI wrote: |
---|
I am not 100% sure why to be honest |
Array indexes start at zero. If one had an array with 10 elements: the first index is 0, the last element would have index of 9.
Consider this:
1 2 3 4 5 6
|
constexpr ArraySize {10}; // array size must be const, constexpr is stronger than const
int MyArray[ArraySize];
for (std::size_t Counter {0}; Counter < ArraySize ; Counter++ ) {
MyArray[Counter] = 0;
}
|
With std::vector one does not need to worry about the size*, it will resize automatically, it does dynamic memory behind the scenes safely - no need for operator
new
or pointers.
* One can reserve the size for a vector, so that all the memory is allocated at once, rather than the compiler having to std::move the contents multiple times as it grows large. There is a strategy for memory allocation as a vector grows, it might say double in size each time it reaches it's max size. But if one knew there were going to be 1 million elements, then it's better to reserve that space once at the start.
ne555 pointed out earlier that you could use
std::vector<std::complex>
, I am wondering if you were aware that STL containers can also hold a class or struct type that you might invent yourself?
1 2 3 4 5
|
struct DataItem {
double time {0.0}; // brace intialisation compiler warns about narrowing if one puts an int say.
double momentum {0.0};
double temperature {0.0};
};
|
//
https://en.cppreference.com/w/cpp/container/vector/vector
std::vector<DataItem> MyData(10); // 10 default inserted DataItem's
Range based for loop
https://en.cppreference.com/w/cpp/language/range-for
Good Luck !!