0

Is there a good reason to set array size?

So if I omit the size it just automatically makes the size I need so what exactly is the point in setting the size that I am not seeing?

11th Dec 2018, 7:51 AM
Jacob Moore
Jacob Moore - avatar
3 Antworten
+ 2
If you initialize the array when you declare it, you can omit the size as it will automatically generated based on the initialization. But if you declare an array and assaing values to it later, then you have to declare the size, that is because the array size is not mutable once declared! For example: int arr[] = {1, 2, 3}; it’s valid because array is initialized when declared, so the program will know that it is an array containing 3 elements. On the other hand: int arr[]; arr[0] = 1; will generate an error, because array size is not known and the size cannot change once declared, because in this case you try to assign a value to the index 0 of the array but still the program doesnt know where it will ends. While: int arr[3]; arr[0] = 1; is a valid input because the program knows that the array can store up to 3 value and until you assign them it will assign them a 0 value! Hope it helps!
11th Dec 2018, 11:05 AM
Sekiro
Sekiro - avatar
+ 1
What language do you mean? Jacob Moore? Please specify it :)
11th Dec 2018, 10:06 AM
ShortCode
0
c++
11th Dec 2018, 10:07 AM
Jacob Moore
Jacob Moore - avatar