0
Can someone explain me the logic behind this array?
Hello! So, I've come across the following C++ code, and I couldn't understand why the array couldn't store more than 8 values. #include <stdio.h> #include <math.h> #include <string.h> int main(void) { int number, d, numberd = 0, array[numberd], counter = 0; scanf("%d",&number); for (d = 1; d <= number; d++){ if (number % d == 0){ array[counter] = d; counter++; numberd++; } } for(counter =0; counter < numberd; counter++){ printf("%d\n",array[counter]); } return 0; }
2 Answers
+ 1
Using variable length array ( array[number] ) with an uninitialised size ( "number" in this case ) is an undefined behaviour, it's much better to move the declaration of array after you have read input from stdin.
Still a lot of extra caution must be practiced while using VLAs( variable length arrays ) as they you might run into issues where stdin may contain a massive number, resulting in creation of equally massive array in your stack memory making your program not only slow, but also vulnerable to stack overflow.
This was one of the reasons that VLAs are not allowed in C++ and only exist in C ( though some c++ compilers do support it as non-standard extensions )
0
I forgot to change some pieces of the code.
But what I didn't get is, the array starts with 0 spaces, then it grows as the variable "numberd" grows, but once "numberd" = 9 or higher, the array doesn't store any value