Array

作者: 某右衛門 | 来源:发表于2016-12-06 00:35 被阅读16次

LT6 Array (1D and 2D)

Definition

Sequence of data items of same type
Stored continuously in memory, indexed by index / subscript

data_type array_name[size];

char str[20]; // ten elements in str: str[0] ... str[19]

N.B.: str[20] is out of bound

The array size is a constant

Initialization of Array

Defining an array only allocates its memory space. The value in the memory is random without initialization.

Therefore arrays need to be initialized after definition:

Bootstrappy Initialization
int k[20];
for (int i=0;i<20;i++)
    k[i]=0;
A More Brilliant Way using { braces }
// Basic Initialization
int a[2] = {1,2};
// Initialization without Size
int a[ ] = {1,2}; // automatically assign to a[2]
// Partial Initialization 
int a[5] = {1,2}; // {1,2,0,0,0}
// Initialization to All Zeros
int a[2] = {0}; // {0,0} 

The listed value are assigned to the respective elements

The remaining elements are assigned to be 0 by default

Comparison between Arrays

Arrays cannot be compared directly via == operator.

(Arrays are pointers pointing to memory addresses in nature)

Have to use for loop to compare the elements one-by-one

Multi-Dimensional Arrays

Multi-Dimentional Array has more than one index

It is a logical representation rather than physical representation.

In memory, the elements are stored in continuous memory space

e.g.: int page[10][300]; has the same memory space as int page[30000];

Stored in "Row-Major" order: Indexed by row (Against column-major order)

  • First block will store page[0][0] - page[0][299], followed by page[1][0] - page[1][299]

!!! Dynamic Memory Allocation

int *s1; // Init the pointer only;
s1 = new int[4]; // create an array of int[4] in memory, point s1 to the new array
cin>>s1[0]>>s1[1]>>s1[2]>>s1[3];
delete [] s1; //destroy the memory space after use;

Steps of Dynamic Memory Allocation

  1. Define the Pointer: int * ptr;
  2. Allocate the Memory: ptr = new int[10];
  3. Do whatever you want
  4. Destroy the memory: delete [] ptr
  5. Point the pointer to NULL ptr = NULL

相关文章

网友评论

      本文标题:Array

      本文链接:https://www.haomeiwen.com/subject/kkilmttx.html