int score[100]; // Can store scores for 100 students. score[ 0] = 87; // Student 1's score is 87. score[85] = 93; // Student 86's score is 93.This allows random access to any data by using the index ( the student number in this case). However note that the indices run from 0 to the allocated number - 1. Therefore it is necessary in some cases, such as the above, to remember a translation in the indices until you get used to the concept of counting from 0.
The dimension of an array can naturally be extended to more than 1. Consider the following example.
int score[2][100]; // Can store scores for students // in 2 classes of 100 each. int score[1][35] = 76; // The score of student 36 in // class 2 is 76.. // Note that this is class 2 since indices start at 0.
char a_Name[20];The string can hold one less than the number of storage defined. The extra space is required for the character
'\0'
(called the
NULL character). This character is used to indicate the end of the string.
For example, the following storage will be used if a_Name is assigned the
value "Class". a_Name[0] = 'C' a_Name[1] = 'l' a_Name[2] = 'a' a_Name[3] = 's' a_Name[4] = 's' a_Name[5] = '\0'
Strings are a special case of arrays since multiple array locations can be assigned a value by one statement such as
a_Name = "My example";Note the use of double quotes to identify strings as opposed to the single quotes used to identify characters. The trailing '\0' need not be explicitly added when using double quotes.
int PhoneNo = 2525; // Variable to store phone number. int *pointer_to_PhoneNo; // Variable that can store an // address to an integer. pointer_to_PhoneNo = &PhoneNo; // Obtain the memory address. cout << PhoneNo; // Prints out 2525. cout << *pointer_to_PhoneNo; // Prints out 2525. cout << pointer_to_PhoneNo; // Prints out some number used // as memory address.Note the following in this example.
short *pointer_short; long *pointer_long; ...... *( pointer_short + 4 ) = 55; // Leaves storage for four shorts // from the start to where 55 is stored. *( pointer_long + 4 ) = 55; // Leaves storage for four longs // from the start to where 55 is stored.The first storage space left might be 4 bytes where as the second one might be 16 bytes. The pointer arithmetic automatically takes care of how much storage is needed based on the type of the pointer.
The usual use of pointer arithmetic is in accessing items in arrays. Example : If my_String contains "cat"
my_String[2] = 'p';changes my_String to "cap".