compiler complains (Variable-sized object may not be initialized)
-
Variable-sized object may not be initializedclang(variable_object_no_init)
void someFunction(int n){ int Array[n] = {0}; // n is unknown until the fucntion recieves a value. }
i tried with some "if else" statements to set the array 1 untill n is known, but the results are the same.
what is the proper way?
-
Static arrays must have a compile-time known size. What you wrote is actually invalid. If your function must allocate an array which size is known only at runtime, you should do
void someFunction(int n){ int* result = new int[n]; }
Then you must handle the object lifetime, i.e. properly call
delete []
once you don't need it anymore, or usestd::unique_ptr< int[] >
for instance. -
thnx, i saw people declare an array like that, but sofar i didn't payed attention to it, because the "riddles" i'm doing went all well.
i changed it to your input, but not the program crashes.
i have to have the first value initiated to zero.int *Array = new int[n]; for (int i = 0; i < n; i++) { Array[i] = 0; } // 0r int *Array = new int[n]; /* for (int i = 0; i < n; i++) { Array[i] = 0; } */
malloc.c:2379: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
-
@JohanSolo is of course correct,
but since you earlier posted, that you're on a journey to discover c++, let me introduce you to this solution:int main() { constexpr int Array [4] = {0}; std::cout << Array[0] << Array[1]<< Array[2]<< Array[3] << '\n'; }
has of course, the downside, its constexpr and therefore cannot be overwritten during run time. But I'm not sure, if that is a requirement for you or not?
-
@Natural_Bugger OK, I didn't know you're discovering C++.
In C++, it's more common to usestd::vector
instead of static arrays in that case. Those can be resized at any time, have constructors which allows to set all values to an initial one. Your initial snippet would read:void someFunction(int n){ std::vector< int > Array( n, 0 ); }
And each element would be accessed by
Array[ i ]
as with a static array. Please note that @J-Hilk's nice solution won't work if the array size is only known at runtime, i.e.void someFunction(int n){ A< n > Array(); }
isn't valid and won't compile.
About the crash you're reporting, I'm afraid I lack information on exactly what you're doing and how.
-
thnx, in the end i changed the program into vector and solved the riddle.
vector<int> Array; int setter = 1; for(int i = 0; i < n; i++){ Array.push_back(setter); setter++; }