Shiny Language Reference
Language Reference > Basic Language
realloc
realloc(varname, int Size);
Synonyms:
redim(varname, int Size);
resize(varname, int Size);
Increases or decreases the size of an array
The REALLOC statement immediately alters the space allocated to an array variable so that it may hold exactly the number of elements specified. REALLOC can increase or decrease the size of the array. If REALLOC is passed a size equal to the current size of the specified array, no action is taken. You may use getalloc to determine the current size of an array.
REALLOC may only be used on variables that have been declared as arrays. If REALLOC is supplied with a variable that is not declared as an array the compiler will generate an error.
Important note regarding REALLOC: There is a speed penalty for resizing arrays, especially when increasing the size of an array. When an array is resized resources must be freed or allocated as appropriate to match the requested size (as opposed to using the declared size, which is set by the Virtual Machine when the SSE is loaded). Resizing an array up (increasing the number of elements it can store) is approximately twice as slow as resizing it down (decreasing the number of elements). It is best practice therefore to declare a variable array with what you believe is a reasonable number of elements, and decrease it if needed (in contrast to declaring an array with only a few elements and increasing it when needed). However declaring overly large arrays is just as inefficient. Some examples for clarity:
- A plugin that loads between 10 and 20 images depending on configuration would declare an array with 20 elements and size down if needed
- A plugin that stores 10 pieces of information except in special circumstances where it stores 15 would declare an array with 10 elements and size up if needed
Note that array reallocation is performed inside the Virtual Machine without making calls back into the SSE, therefore speed penalties are relative (in other words, the reallocation is performed via native x86 rather than through the SSE VM).
Parameters
Varname
The variable, declared as an array, to resize.
Size
The new number of elements this array should hold. Remember that arrays are zero-based access, therefore specifying 10 for this parameter will give an array with elements 0 to 9.
Return Value
No return value.
Example Code
// Declare an array with 5 elements
int test[5];
for(int ic = 0; ic < getalloc(test); ic++)
{
// Set and print an example value
test[ic] = ic * 10;
print test[ic];
}
print "Resizing array...";
// Reduce the array to only hold 3 elements
realloc(test, 3);
for(ic = 0; ic < getalloc(test); ic++)
{
// Set and print an example value
test[ic] = ic * 10;
print test[ic];
}