c++ changing array size - is it black magic or an illusion? šŸ¤” | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
0

c++ changing array size - is it black magic or an illusion? šŸ¤”

Traditional rules state array size cannot change. however, with this array function it appears the array is changing in size. So question for the experts: is it actually changing size? Or is it an illusion (the array actually has 22 idx and only reports how many are being used)? I honestly don't have a clue! The array size is initially set at 7. Yet it is eventually increased to 22 and back to 5. However, in the other example (c++ array size), the array is set to have 5 idx. Even as they are empty, the size is always reported as 5. But in the case of the function, the array size *is* actually being reported as changing... And while size_arr is being passed to the function, the cout of the function never actually references that variable, it should only report the actual size: cout << sizeof(arr)/sizeof(int) << endl; as it does in the accompanying example. So, is it black magic or an illusion? https://code.sololearn.com/cB7UChgXGIGJ/?ref=app https://code.sololearn.com/cCBZXjZzTx17/?ref=app

9th Dec 2022, 5:38 AM
Scott D
Scott D - avatar
3 Respostas
+ 2
KrOW You're probably right, I'm probably "gaming the system" so to speak. Even though the array name doesn't change each time the function is called it's a new array, but with the same name. I'm a newbie but not aware that there's any changes regarding making array lengths variable. I guess that's why there are vectors. Wouldn't a compiler allowing that be kind of bad? I don't know much about compilers but would think that if the code was run on a different compiler or OS there could be errors.
9th Dec 2022, 7:16 AM
Scott D
Scott D - avatar
+ 1
The array, tecnically, is not changing.. Every time that you call the randArr function a new stack frame is created and a new array is allocated with specified size. Anyway, i dont be update of c++ standards, but variable length array would be an extension of compiler not part of c++ standard. In theory : int a= 7; int c[a]; would be compilable in c++ specs from what i remember
9th Dec 2022, 7:07 AM
KrOW
KrOW - avatar
+ 1
it seem that gcc and clang support it but can be disabled ... I dont know if and why is supported by default by compilers (maybe some flag used by SL compiler?)
9th Dec 2022, 7:32 AM
KrOW
KrOW - avatar