Questions tagged [arrays]

An array is an ordered linear data structure consisting of a collection of elements (values, variables, or references), each identified by one or more indexes. When asking about specific variants of arrays, use these related tags instead: [vector], [arraylist], [matrix]. When using this tag, in a question that is specific to a programming language, tag the question with the programming language being used.

An array is an ordered linear data structure consisting of a collection of elements (values or variables), each identified by at least one index, stored in contiguous memory locations.

An array is typically stored so that the position of each element can be computed from its index tuple by a mathematical formula.

In some languages (C, Java, etc.) the length of the array must be set beforehand. In other languages (Ruby, Python, LISP, Haxe, etc.) the length of the array grows dynamically as elements are added.

When tagging a question with this tag, also tag the question with the programming language being used.

Array in specific languages

  • C# arrays are actually objects and not just addressable regions of contiguous memory as in C and C++. Array is the abstract base type of all array types. You can use the properties and other class members of the Array base type.
  • C arrays act to store related data under a single variable name with an index, also known as a subscript. They are stored in row-major order, which means the last subscript varies fastest. It is easiest to think of an array as simply a list or ordered grouping for variables of the same type. As such, arrays often help a programmer organize collections of data efficiently and intuitively.
  • C++ inherits raw arrays from C and adds its own array-class std::array for compile-time array sizes, std::vector for runtime dynamic sized arrays. It also has smart pointer implementations like std::unique_ptr, std::shared_ptr.
  • Objective C inherits raw arrays from C and adds its own array-class NSArray and NSMutableArray for dynamic arrays.
  • Ruby's normal array class is called array.
  • In Python, the normal array datatype is called a list, while the array type is used for homogeneous arrays.
  • In NumPy there is a powerful N-dimensional array with many capabilities.
  • PHP arrays are implemented as ordered maps which may contain a mix of numeric or string keys.
  • JavaScript arrays are just objects with a different prototype (with additional functions more useful for array-like structures), with numerical index values stored as strings (all JavaScript keys are strings). Unlike other objects, you cannot use dot notation to access keys - only square bracket notation.
  • In Haxe, an Array has one type parameter which corresponds to the type of collection of elements. Arrays can be created using their constructor new Array() or [1, 2, 3], but also using Array comprehension: [for (i in 0...10) if (i % 2 == 0) i]. For storage of fixed size the abstract type haxe.ds.Vector can be used, which may be faster than Array on some targets and is never slower.
  • In Scala, the normal array class is called Array. To get an element from an array you use parentheses (most languages use square brackets).
  • In Java, an array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
  • In Perl, array variables are denoted with the @ prefix and arrays are declared with parentheses. Replacing the prefix with $# returns the last index.
  • In Rust, arrays are groups of data of the same type that are contiguous in memory, so they can be used when communicating with C. The length of an array is fixed.
  • In Swift, an array that includes the specified values, automatically inferring the array’s Element type. Swift makes it easy to create arrays in your code using an array literal: simply surround a comma-separated list of values with square brackets.
  • In Pascal, arrays declarations specify the index range rather than the number of elements; so parray: array [1..25] of real; declares a one-based array of 25 real numbers (valid elements are parray[1] thru parray[25]), whereas parray: array [0..24] of real; declares a zero-based ('C-style') array of the same size (the first element is parray[0]). Pascal array index ranges can include negative numbers!

Characteristics

Elements of an array are usually specified with a 0-first index, for example, myarray[0] would represent the first element of myarray. myarray[n] (where n is the length of the array minus 1) would represent the last element in the array. However, some languages such as old Fortran and Lua use 1 as the initial index.

Some languages (C++, Java, C#) have "basic arrays" and collections. Basic arrays are supported by the compiler directly, have a fixed size, and only provide element access by index. Collections, like Java's ArrayList, are system library classes implemented on the top of these basic arrays and have a wide range of various methods. In such cases, the tag should be used to name the simple arrays.

Arrays can be statically allocated or dynamically allocated. The way in which you access the array and its type varies based on how it is declared and allocated.

Arrays can contain multiple indices. For example, an array with one index (e.g. array[0]) is known as a one-dimensional array. If it has two indices (e.g. array[0][0]) it is considered two dimensional and maybe visualized as a grid. Multidimensional arrays, or, in other words, arrays with multiple indices are called matrices, or a matrix is singular.

References

Related tags

Where talking about specific variants of arrays, use these related tags instead:

414766 questions
76
votes
12 answers

Resize an Array while keeping current elements in Java?

I have searched for a way to resize an array in Java, but I could not find ways of resizing the array while keeping the current elements. I found for example code like int[] newImage = new int[newWidth];, but this deletes the elements stored…
Mihai Bujanca
  • 4,089
  • 10
  • 43
  • 84
76
votes
7 answers

Passing an array by reference in C?

How can I pass an array of structs by reference in C? As an example: struct Coordinate { int X; int Y; }; SomeMethod(Coordinate *Coordinates[]){ //Do Something with the array } int main(){ Coordinate Coordinates[10]; …
Hannoun Yassir
  • 20,583
  • 23
  • 77
  • 112
76
votes
7 answers

Array of hashes to hash

For example, I have array of single hashes a = [{a: :b}, {c: :d}] What is best way to convert it into this? {a: :b, c: :d}
evfwcqcg
  • 15,755
  • 15
  • 55
  • 72
76
votes
9 answers

Difference between array type and array allocated with malloc

Today I was helping a friend of mine with some C code, and I've found some strange behavior that I couldn't explain him why it was happening. We had TSV file with a list of integers, with an int each line. The first line was the number of lines the…
Jorge Leitao
  • 19,085
  • 19
  • 85
  • 121
75
votes
8 answers

c++ array - expression must have a constant value

I get an error when I try to create an array from the variables I declared. int row = 8; int col= 8; int [row][col]; Why do I get this error: expression must have a constant value.
Nicholas Kong
  • 1,083
  • 4
  • 14
  • 14
75
votes
6 answers

Is reading the `length` property of an array really that expensive an operation in JavaScript?

I always assumed caching the length of an array in JavaScript is a good idea (especially in the condition of a for loop) because of the expensiveness of calculating the length of an array. Example for (var i = 0; i < arr.length; i++) { } // vs for…
alex
  • 479,566
  • 201
  • 878
  • 984
75
votes
13 answers

Find a matching or closest value in an array

How can I search and find, for a given target value, the closest value in an array? Let's say I have this exemplary array: array(0, 5, 10, 11, 12, 20) For example, when I search with the target value 0, the function shall return 0; when I search…
FMaz008
  • 11,161
  • 19
  • 68
  • 100
75
votes
8 answers

find if an integer exists in a list of integers

i have this code: List apps = getApps(); List ids; List dropdown = apps.ConvertAll(c => new SelectListItem { Selected = ids.Contains(c.Id), Text = c.Name, Value…
leora
  • 188,729
  • 360
  • 878
  • 1,366
75
votes
1 answer

Why define \0 as the first element of a char array in C?

When I read BlueZ source code, I often see char arrays defined like this: // bluez/android/sco-msg.h static const char BLUEZ_SCO_SK_PATH[] = "\0bluez_sco_socket"; What good is it to define the first element as \0?
user1923105
  • 713
  • 5
  • 9
75
votes
1 answer

Is a JavaScript array order guaranteed?

Assuming a JavaScript array is posted in a form (using ajax/JQuery) is the order in the array guaranteed? Valid question from @Quentin "Define 'posted in a form'" $.ajax({ type: "POST", url: url, data: { foo: [{ name: "one" }, { name: "two" }]…
Rafael Herscovici
  • 16,558
  • 19
  • 65
  • 93
75
votes
3 answers

Vuejs: v-model array in multiple input

I have an input text field with a v-model attached, and every time someone hits the "Add" button, another input text gets added to the DOM with the same v-model attached. I thought I'd then get an array of the v-model values, but it only gets the…
jlos
  • 1,010
  • 1
  • 8
  • 12
75
votes
6 answers

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

here is my use case in JavaScript: I have two arrays of objects which have properties that match (id & name). var result1 = [ {id:1, name:'Sandra', type:'user', username:'sandra'}, {id:2, name:'John', type:'admin', username:'johnny2'}, …
Leo
  • 5,363
  • 5
  • 27
  • 30
75
votes
9 answers

how to convert image to byte array in java?

I want to convert an image to byte array and vice versa. Here, the user will enter the name of the image (.jpg) and program will read it from the file and will convert it to a byte array.
userv
  • 2,527
  • 4
  • 27
  • 36
75
votes
3 answers

C# 4.0: Convert pdf to byte[] and vice versa

How do I convert a pdf file to a byte[] and vice versa?
xscape
  • 3,318
  • 9
  • 45
  • 86
75
votes
8 answers

How can I create an array/list of dictionaries in python?

I have a dictionary as follows: {'A':0,'C':0,'G':0,'T':0} I want to create an array with many dictionaries in it, as follows: [{'A':0,'C':0,'G':0,'T':0},{'A':0,'C':0,'G':0,'T':0},{'A':0,'C':0,'G':0,'T':0},...] This is my code: weightMatrix =…
Adrian Randall
  • 751
  • 1
  • 5
  • 3