I want to define an array in my BEGIN statement with undefined index number; how can I do this in AWK?
BEGIN {send_packets_0to1 = 0;rcvd_packets_0to1=0;seqno=0;count=0; n_to_n_delay[];};
I have problem with n_to_n_delay[].
Dynamic arrays in C++ are declared using the new keyword. We use square brackets to specify the number of items to be stored in the dynamic array. Once done with the array, we can free up the memory using the delete operator. Use the delete operator with [] to free the memory of all array elements.
In awk , you don't need to specify the size of an array before you start to use it. Additionally, any number or string in awk may be used as an array index, not just consecutive integers. In most other languages, you have to declare an array and specify how many elements or components it contains.
AWK has associative arrays and one of the best thing about it is – the indexes need not to be continuous set of number; you can use either string or number as an array index. Also, there is no need to declare the size of an array in advance – arrays can expand/shrink at runtime.
Syntax: ReDim {Preserve] array_name(subscripts)
info gawk
says, in part:
Arrays in 'awk' superficially resemble arrays in other programming languages, but there are fundamental differences. In 'awk', it isn't necessary to specify the size of an array before starting to use it. Additionally, any number or string in 'awk', not just consecutive integers, may be used as an array index.
In most other languages, arrays must be "declared" before use, including a specification of how many elements or components they contain. In such languages, the declaration causes a contiguous block of memory to be allocated for that many elements. Usually, an index in the array must be a positive integer.
However, if you want to "declare" a variable as an array so referencing it later erroneously as a scalar produces an error, you can include this in your BEGIN
clause:
split("", n_to_n_delay)
which will create an empty array.
This can also be used to empty an existing array. While gawk
has the ability to use delete
for this, other versions of AWK do not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With