- An array is a sequential collection of data storage locations, each of which holds the same type of sata
- Array element offsets are counted from 0
SomeArray[n]
hasn
elements that are numberedSomeArray[0]
throughSomeArray[n-1]
// Inialize an array
int myArray[5]; // Empty Array of 5 integers
int IntegerArray[5] = {10, 20, 30, 40, 50};
int IntArray[] = {1, 2, 3, 4, 5, 6}; // Compiler automatically picks the array size!
Cpp-in-21-days-Part4/Day 13 - Arrays/const_and_enum_in_Arrays.cpp
Lines 3 to 11 in 659f340
- DON'T write value into an array past the initialized size! The program may crash
- You cannot initialize more elements than you've declared for the array
- When you declare the array to hold objects, you tell the compiler the type of object to store and the number
- The class MUST have a default constructor (takes no arguments) so that the object can be created
Cpp-in-21-days-Part4/Day 13 - Arrays/Arrays_of_Objects.cpp
Lines 5 to 32 in 659f340
int theArray[5][3] = { {1,2,3},
{4,5,6},
{7,8,9},
{10,11,12},
{13,14,15}}; // for easy understanding
- An array of characters that is terminated by a null
- Ex:
char Greeting[] =
{'H','e','l','l','o', ' ', 'W','o','r','l','d','\0'};
// This is equivalent to
char Greeting2[] = "Hello World";
- The last character,
\0
, is the null character, telling c++ to terminate - For double-quoted string, the compiler automatically add the null character for you
Hello World
is 12 bytes: Hello=5 bytes, space=1byte, World=5 bytes, and the null character is 1 byte
strcpy(String2, String1)
copies the entire contents of one string into a designated bufferstrncpy(String2, String1, MaxLength)
copies a number of characters from one string to another- If the source is larger than the destination,
strcpy()
overwrites past the end of the buffer
Cpp-in-21-days-Part4/Day 13 - Arrays/using_strcpy.cpp
Lines 1 to 16 in 5c19cf1
Cpp-in-21-days-Part4/Day 13 - Arrays/using_strncpy.cpp
Lines 1 to 16 in 5c19cf1