Reputation: 21
If I declare an array of size 20, and the number of value I will give is 9, so will the array occupy total of 20 size space in the memory or it will only occupy 9?
Upvotes: 2
Views: 1237
Reputation: 234715
As far as you are concerned it's going to be 20.
The as-if rule allows it to be less than 20 or even compiled out altogether, although I don't know of a compiler that would exploit the former even if elements of the array were accessed with only compile-time evaluable indexing.
Note that sizeof array / sizeof element
would have to return 20 which further complicates matters.
Upvotes: 4
Reputation: 21
It will occupy 20.
The compiler will allocate the memory size of the array(here 20) at the compile time, and that memory can not be used by other data structures.Regardless of how much memory you actually use(here 9) , all the 20 blocks will be "reserved" for the array.
Upvotes: 2
Reputation: 67526
You need to use dynamic memory allocation if you want to have runtime size sortable library. You can use VLAs but it is only limited to the automatic storage variables and it's size cannot be changed before exiting the scope.
You can use malloc family functions allocating memory to the pointers which can be used same way as arrays (but for example you can't use sizeof method to determine the size of it)
Upvotes: 0
Reputation: 134336
Unless it's a VLA, array size is a compile time constant, so it does not matter how much memory you're actually using, it will take up the amount of memory same as the size of the array given at the time of definition.
In other words, an array defined like
int arr[20] = {0};
is going to occupy the memory for size of 20 int
elements, i.e., the size of the array would be int [20]
.
You can check the size occupied by running
int arr[20] = {0};
printf ("size of the array: %zu", sizeof (arr));
Upvotes: 1