In the case I am creating an 'array' on stack in c , is it better to initialise an empty vector with a reserved number of elements and then pass this to a function like foo()
as a reference as below. Or is it better to set an array arrb
of size nelems
, then using a pointer p_arrb
to the address of the first element increment the pointer and assign some value?
#include <iostream>
#include <vector>
void foo(std::vector<int>& arr){
int nelems = arr.capacity();
for (int i = 0; i < nelems; i ){
arr[i] = i;
}
}
int main()
{
int nelems;
std::cout << "Type a number: "; // Type a number and press enter
std::cin >> nelems;
std::vector<int> arr;
arr.reserve(nelems); // Init std lib vector
foo(arr);
int arrb[nelems];
int* p_arrb = &(arrb[0]); // pointer to arrb
for (int i = 0; i < nelems; i ){
*(p_arrb ) = i; // populate using pointer
}
p_arrb -= nelems; // decrement pointer
return 0;
}
It seems people prefer the use of vector as it is standardised and easier to read? Apart from that, is there any performance benefit to using vector instead of a basic pointer in this case where I do not need to change the size of my vector/array at any point in the code?
CodePudding user response:
What you should use depends on the exact goal you have. In general the best approach is to avoid using "raw arrays" (both dynamic and static) wherever possible.
If you need dynamic array, use std::vector
. If you need static array, use std::array
.
CodePudding user response:
You can't use the arrb
variant because the size of an array must be a compile-time constant in C , but you are trying to use a runtime size here.
If your compiler is compiling this, then it is doing so only because it supports these so-called variable-length arrays as a non-standard extension. Other compilers will not support them or have differing degree of support or behavior. These arrays are optionally-supported in C, but even there they are probably not worth the trouble they cause.
There is no way to allocate a runtime-dependent amount of memory on the stack in C (except if you misuse recursive function calls to simulate it).
So yes, you should use the vector
approach. But as discussed in the comments under the question, what you are doing is wrong and causes undefined behavior. You need to either reserve
memory and then emplace_back
/push_back
elements into the vector or you need to resize
the vector to the expected size and then you may index it directly. Indexing a vector outside the the range of elements already created in it causes undefined behavior.