Arrays, Vectors, and Strings Allocation and referencing
Array Type • Arrays are a compound type • Base_type name[size]; • Array dimension specifies the number of elements • Dimension must be a positive integer literal OR a constant expression (i. e. , known at compile time)
Array Examples cnt = 100; // not a const expr constexpr max = 100; // a const expr int array 1[100]; // good int array 2[max]; // good int array 3[cnt]; // error – not const int array 4[getsize(something)]; // good iff getsize() is constexpr
Arrays • Array indices run from 0 to Max-1 • Always check your index!! • Can reference element by index or by pointer dereference • A[i] or *(A + i) • Type allows compiler to compute correct offset into memory
Arrays int array 1[5]={1, 2, 4, 8, 16}; RAM char name[5]=“Mary”; int *ptr = &array 1[0]; Symbol Table Identifier Type Location array 1 int* 0 xfa 18 name char* 0 xfa 2 c ptr int* 0 xfa 18 Note: null terminated ‘ ’ ‘y’ ‘a’ ‘r’ ‘M’ 0 x 00000010 0 x 00000008 0 x 00000004 0 x 00000002 0 x 00000001 Address 0 xfa 58 0 xfa 54 0 xfa 50 0 xfa 4 c 0 xfa 48 0 xfa 44 0 xfa 40 0 xfa 3 c 0 xfa 38 0 xfa 34 0 xfa 30 0 xfa 2 c 0 xfa 28 0 xfa 24 0 xfa 20 0 xfa 1 c 0 xfa 18 0 xfa 14 0 xfa 10
2 -D Arrays • C++ does not really have multi-D arrays • Looks kind of like it: int A[M][N]; • Arrays are really pointers to the first element in a consecutively stored sequence of elements of same type • 2 -D array is really pointer to a 1 -D array of pointers to first row elements
C-Style Strings • C++ has a String class • Can be referenced by index like array • But it is a true object • C strings are not a primitive type, nor are they a struct • A C-style string is just a 1 -D array of char, with NULL termination • NOTA BENE: always a '