An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). 数组是元素的集合,存储在连续的内存空间,类型一样,有利于计算每个元素的位置,在基数上增加偏移即可。

Types of indexing in array:
- 0 (zero-based indexing): The first element of the array is indexed by subscript of 0 下标从0开始的
- 1 (one-based indexing): The first element of the array is indexed by subscript of 1 下标从1开始的
- n (n-based indexing): The base index of an array can be freely chosen. Usually programming languages allowing n-based indexing also allow negative index values and other scalar data types like enumerations, or characters may be used as an array index.

Advantages of using arrays:
- Arrays allow random access of elements. This makes accessing elements by position faster. array可以随机访问,
- Arrays have better cache locality that can make a pretty big difference in performance.
Examples –
// A character array in C/C++/Java
char arr1[] = {'g', 'e', 'e', 'k', 's'};
// An Integer array in C/C++/Java
int arr2[] = {10, 20, 30, 40, 50};
// Item at i'th index in array is typically accessed
// as "arr[i]". For example arr1[0] gives us 'g'
// and arr2[3] gives us 40.
Arrays in C/C++
An array is collection of items stored at continuous memory locations.
Why do we need arrays?
We can use normal variables (v1, v2, v3, ..) when we have small number of objects, but if we want to store large number of instances, it becomes difficult to manage them with normal variables. The idea of array is to represent many instances in one variable.
Array declaration in C/C++:

We can declare an array by specifying its type and size or by initializing it or by both.
- Array declaration by specifying size
// Array declaration by specifying size
int arr1[10];
// With recent C/C++ versions, we can also
// declare an array of user specified size
int n = 10;
int arr2[n];
- Array declaration by initializing elements
// Array declaration by initializing elements
int arr[] = { 10, 20, 30, 40 }
// Compiler creates an array of size 4.
// above is same as "int arr[4] = {10, 20, 30, 40}"
- Array declaration by specifying size and initializing elements
// Array declaration by specifying size and initializing
// elements
int arr[6] = { 10, 20, 30, 40 }
// Compiler creates an array of size 6, initializes first
// 4 elements as specified by user and rest two elements as 0.
// above is same as "int arr[] = {10, 20, 30, 40, 0, 0}"
Facts about Array in C/C++:
- Accessing Array Elements:
Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of array minus 1.
Following are few examples.
#include <stdio.h>
int main()
{
int arr[5];
arr[0] = 5;
arr[2] = -10;
arr[3 / 2] = 2; // this is same as arr[1] = 2
arr[3] = arr[0];
printf("%d %d %d %d", arr[0], arr[1], arr[2], arr[3]);
return 0;
}
- Output:
5 2 -10 5
- No Index Out of bound Checking:
There is no index out of bound checking in C, for example the following program compiles fine but may produce unexpected output when run.
// This C program compiles fine
// as index out of bound
// is not checked in C.
#include <stdio.h>
int main()
{
int arr[2];
printf("%d ", arr[3]);
printf("%d ", arr[-2]);
return 0;
}
- Output:
2008101287 4195777
- Also, In C, it is not compiler error to initialize an array with more elements than specified size. For example the below program compiles fine and shows just Warning.
#include <stdio.h>
int main()
{
// Array declaration by initializing it with more
// elements than specified size.
int arr[2] = { 10, 20, 30, 40, 50 };
return 0;
}
-
Warnings:
prog.c: In function 'main': prog.c:7:25: warning: excess elements in array initializer int arr[2] = { 10, 20, 30, 40, 50 }; ^ prog.c:7:25: note: (near initialization for 'arr') prog.c:7:29: warning: excess elements in array initializer int arr[2] = { 10, 20, 30, 40, 50 }; ^ prog.c:7:29: note: (near initialization for 'arr') prog.c:7:33: warning: excess elements in array initializer int arr[2] = { 10, 20, 30, 40, 50 }; ^ prog.c:7:33: note: (near initialization for 'arr')
The program won’t compile in C++. If we save the above program as a .cpp, the program generates compiler error “error: too many initializers for ‘int [2]'” - An Example to show that array elements are stored at contiguous locations
// C program to demonstrate that array elements are stored
// contiguous locations
#include <stdio.h>
int main()
{
// an array of 10 integers. If arr[0] is stored at
// address x, then arr[1] is stored at x + sizeof(int)
// arr[2] is stored at x + sizeof(int) + sizeof(int)
// and so on.
int arr[5], i;
printf("Size of integer in this compiler is %lu\n", sizeof(int));
for (i = 0; i < 5; i++)
// The use of '&' before a variable name, yields
// address of variable.
printf("Address arr[%d] is %p\n", i, &arr[i]);
return 0;
}
- Output:
Size of integer in this compiler is 4 Address arr[0] is 0x7ffd636b4260 Address arr[1] is 0x7ffd636b4264 Address arr[2] is 0x7ffd636b4268 Address arr[3] is 0x7ffd636b426c Address arr[4] is 0x7ffd636b4270
Array vs Pointers
Arrays and pointer are two different things (we can check by applying sizeof). The confusion happens because array name indicates address of first element and arrays are always passed as pointers (even if we use square bracket). Please see Difference between pointer and array in C?for more details.
What is vector in C++?
Vector in C++ is a class in STL that represents an array. The advantages of vector over normal arrays are,
- We do not need pass size as an extra parameter when we pass vector. 传递vector时不需要传递大小。
- Vectors have many in-built function like, erasing an element, etc. vector有许多内建函数
- Vectors support dynamic sizes, we do not have to initially specify size of a vector. We can also resize a vector.vector允许动态大小,不需要显示表示vector的大小
- There are many other functionalities vector provide, please refer vector in C++ for more details.
Arrays in Java
An array is a group of like-typed variables that are referred to by a common name.Arrays in Java work differently than they do in C/C++. Following are some important point about Java arrays.
- In Java all arrays are dynamically allocated.(discussed below) Java的array是动态分布。
- Since arrays are objects in Java, we can find their length using member length. This is different from C/C++ where we find length using sizeof.
- A Java array variable can also be declared like other variables with [] after the data type.
- The variables in the array are ordered and each have an index beginning from 0.
- Java array can be also be used as a static field, a local variable or a method parameter.
- The size of an array must be specified by an int value and not long or short.
- The direct superclass of an array type is Object.
- Every array type implements the interfaces Cloneable and java.io.Serializable.
Array can contains primitives data types as well as objects of a class depending on the definition of array. In case of primitives data types, the actual values are stored in contiguous memory locations. In case of objects of a class, the actual objects are stored in heap segment.
Creating, Initializing, and Accessing an Array
One-Dimensional Arrays :
The general form of a one-dimensional array declaration is
type var-name[]; OR type[] var-name;
An array declaration has two components: the type and the name. type declares the element type of the array. The element type determines the data type of each element that comprises the array. Like array of int type, we can also create an array of other primitive data types like char, float, double..etc or user defined data type(objects of a class).Thus, the element type for the array determines what type of data the array will hold.
Example:
// both are valid declarations
int intArray[];
or int[] intArray;
byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];
// an array of references to objects of
// the class MyClass (a class created by
// user)
MyClass myClassArray[];
Object[] ao, // array of Object
Collection[] ca; // array of Collection
// of unknown type
Although the above first declaration establishes the fact that intArray is an array variable, no array actually exists. It simply tells to the compiler that this(intArray) variable will hold an array of the integer type. To link intArray with an actual, physical array of integers, you must allocate one using new and assign it to intArray.
Instantiating an Array in Java
When an array is declared, only a reference of array is created. To actually create or give memory to array, you create an array like this:The general form of new as it applies to one-dimensional arrays appears as follows:
var-name = new type [size];
Here, type specifies the type of data being allocated, size specifies the number of elements in the array, and var-name is the name of array variable that is linked to the array. That is, to use new to allocate an array, you must specify the type and number of elements to allocate.
Example:
int intArray[]; //declaring array intArray = new int[20]; // allocating memory to array
OR
int[] intArray = new int[20]; // combining both statements in one
Note :
-
- The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types).Refer Default array values in Java
- Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory that will hold the array, using new, and assign it to the array variable. Thus, in Java all arrays are dynamically allocated.
Array Literal
In a situation, where the size of the array and variables of array are already known, array literals can be used.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Declaring array literal
- The length of this array determines the length of the created array.
- There is no need to write the new int[] part in the latest versions of Java
Accessing Java Array Elements using for Loop
Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using Java for Loop.
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
" : "+ arr[i]);
Implementation:
// Java program to illustrate creating an array
// of integers, puts some values in the array,
// and prints each value to standard output.
class GFG
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;
// allocating memory for 5 integers.
arr = new int[5];
// initialize the first elements of the array
arr[0] = 10;
// initialize the second elements of the array
arr[1] = 20;
//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
" : "+ arr[i]);
}
}
Output:
Element at index 0 : 10 Element at index 1 : 20 Element at index 2 : 30 Element at index 3 : 40 Element at index 4 : 50
You can also access java arrays using foreach loops
Arrays of Objects
An array of objects is created just like an array of primitive type data items in the following way.
Student[] arr = new Student[7]; //student is a user-defined class
The studentArray contains seven memory spaces each of size of student class in which the address of seven Student objects can be stored.The Student objects have to be instantiated using the constructor of the Student class and their references should be assigned to the array elements in the following way.
Student[] arr = new Student[5];
// Java program to illustrate creating an array of
// objects
class Student
{
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}
// Elements of array are objects of a class Student.
public class GFG
{
public static void main (String[] args)
{
// declares an Array of integers.
Student[] arr;
// allocating memory for 5 objects of type Student.
arr = new Student[5];
// initialize the first elements of the array
arr[0] = new Student(1,"aman");
// initialize the second elements of the array
arr[1] = new Student(2,"vaibhav");
// so on...
arr[2] = new Student(3,"shikar");
arr[3] = new Student(4,"dharmesh");
arr[4] = new Student(5,"mohit");
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : " +
arr[i].roll_no +" "+ arr[i].name);
}
}
Output:
Element at 0 : 1 aman Element at 1 : 2 vaibhav Element at 2 : 3 shikar Element at 3 : 4 dharmesh Element at 4 : 5 mohit
What happens if we try to access element outside the array size?
Compiler throws ArrayIndexOutOfBoundsException to indicate that array has been accessed with an illegal index. The index is either negative or greater than or equal to size of array.
class GFG
{
public static void main (String[] args)
{
int[] arr = new int[2];
arr[0] = 10;
arr[1] = 20;
for (int i = 0; i <= arr.length; i++)
System.out.println(arr[i]);
}
}
Runtime error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at GFG.main(File.java:12)
Output:
10 20
Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other array. These are also known as Jagged Arrays. A multidimensional array is created by appending one set of square brackets ([]) per dimension. Examples:
int[][] intArray = new int[10][20]; //a 2D array or matrix int[][][] intArray = new int[10][20][10]; //a 3D array
class multiDimensional
{
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
// printing 2D array
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Output:
2 7 9 3 6 1 7 4 2

Passing Arrays to Methods
Like variables, we can also pass arrays to methods.For example, below program pass array to method sum for calculating sum of array’s values.
// Java program to demonstrate
// passing of array to method
class Test
{
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
// passing array to method m1
sum(arr);
}
public static void sum(int[] arr)
{
// getting sum of array values
int sum = 0;
for (int i = 0; i < arr.length; i++)
sum+=arr[i];
System.out.println("sum of array values : " + sum);
}
}
Output :
sum of array values : 15
Returning Arrays from Methods
As usual, a method can also return an array. For example, below program returns an array from method m1.
// Java program to demonstrate
// return of array from method
class Test
{
// Driver method
public static void main(String args[])
{
int arr[] = m1();
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" ");
}
public static int[] m1()
{
// returning array
return new int[]{1,2,3};
}
}
Output:
1 2 3
Class Objects for Arrays
Every array has an associated Class object, shared with all other arrays with the same component type.
// Java program to demonstrate
// Class Objects for Arrays
class Test
{
public static void main(String args[])
{
int intArray[] = new int[3];
byte byteArray[] = new byte[3];
short shortsArray[] = new short[3];
// array of Strings
String[] strArray = new String[3];
System.out.println(intArray.getClass());
System.out.println(intArray.getClass().getSuperclass());
System.out.println(byteArray.getClass());
System.out.println(shortsArray.getClass());
System.out.println(strArray.getClass());
}
}
Output:
class [I class java.lang.Object class [B class [S class [Ljava.lang.String;
Explanantion :
- The string “[I” is the run-time type signature for the class object “array with component type int“.
- The only direct superclass of any array type is java.lang.Object.
- The string “[B” is the run-time type signature for the class object “array with component type byte“.
- The string “[S” is the run-time type signature for the class object “array with component type short“.
- The string “[L” is the run-time type signature for the class object “array with component type of a Class”. The Class name is then followed.
Array Members
Now as you know that arrays are object of a class and direct superclass of arrays is class Object.The members of an array type are all of the following:
- The public final field length, which contains the number of components of the array. lengthmay be positive or zero.
- All the members inherited from class Object; the only method of Object that is not inherited is its clone method.
- The public method clone(), which overrides clone method in class Object and throws no checked exceptions.
Cloning of arrays
- When you clone a single dimensional array, such as Object[], a “deep copy” is performed with the new array containing copies of the original array’s elements as opposed to references.
// Java program to demonstrate
// cloning of one-dimensional arrays
class Test
{
public static void main(String args[])
{
int intArray[] = {1,2,3};
int cloneArray[] = intArray.clone();
// will print false as deep copy is created
// for one-dimensional array
System.out.println(intArray == cloneArray);
for (int i = 0; i < cloneArray.length; i++) {
System.out.print(cloneArray[i]+" ");
}
}
}
-
Output:
false 1 2 3

- A clone of a multidimensional array (like Object[][]) is a “shallow copy” however, which is to say that it creates only a single new array with each element array a reference to an original element array but subarrays are shared.
// Java program to demonstrate
// cloning of multi-dimensional arrays
class Test
{
public static void main(String args[])
{
int intArray[][] = {{1,2,3},{4,5}};
int cloneArray[][] = intArray.clone();
// will print false
System.out.println(intArray == cloneArray);
// will print true as shallow copy is created
// i.e. sub-arrays are shared
System.out.println(intArray[0] == cloneArray[0]);
System.out.println(intArray[1] == cloneArray[1]);
}
}
-
Output:
false true true



被折叠的 条评论
为什么被折叠?



