Variable-length Array - Examples

Examples

The following C function allocates a variable-length array of a specified size, fills it with floating-point values, then passes it to another function for processing. Because the array is declared as an automatic variable, its lifetime ends when the read_and_process function returns.

float read_and_process(int n) { float vals; for (int i = 0; i < n; i++) vals = read_val; return process(vals, n); }

Following is the same example in Ada. Note that Ada arrays carry their bounds with them, there is no need to pass the length to the Process function.

type Vals_Type is array (Positive range <>) of Float; function Read_And_Process (N : Integer) return Float is Vals : Vals_Type (1 .. N); begin for I in 1 .. N loop Vals (I) := Read_Val; end loop; return Process (Vals); end Read_And_Process;

The equivalent Fortran 90 function is:

function read_and_process(n) result(o) integer,intent(in)::n real::o real,dimension(n)::vals real::read_val, process integer::i do i = 1,n vals(i) = read_val end do o = process(vals, n) end function read_and_process

The following COBOL fragment declares a variable-length array of records, DEPT-PERSON, having a length (number of members) specified by the value of PEOPLE-CNT.

DATA DIVISION. WORKING-STORAGE SECTION. 01 DEPT-PEOPLE. 05 PEOPLE-CNT PIC S9(4) BINARY. 05 DEPT-PERSON OCCURS 0 TO 20 TIMES DEPENDING ON PEOPLE-CNT. 10 PERSON-NAME PIC X(20). 10 PERSON-WAGE PIC S9(7)V99 PACKED-DECIMAL.

The following C# fragment declares a variable-length array of integers. The "unsafe" keyword would require an assembly containing this code to be marked as unsafe.

unsafe void declareStackBasedArray(int size) { int *pArray = stackalloc int; pArray = 123; }

Read more about this topic:  Variable-length Array

Famous quotes containing the word examples:

    It is hardly to be believed how spiritual reflections when mixed with a little physics can hold people’s attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.
    —G.C. (Georg Christoph)

    Histories are more full of examples of the fidelity of dogs than of friends.
    Alexander Pope (1688–1744)

    In the examples that I here bring in of what I have [read], heard, done or said, I have refrained from daring to alter even the smallest and most indifferent circumstances. My conscience falsifies not an iota; for my knowledge I cannot answer.
    Michel de Montaigne (1533–1592)