Arrays
A sequence of values back to back (contiguous) in memory all of which is the same data type
Declaration
type name[size];
# individual element syntax
int scores[3];
scores[0] = 72;
scores[1] = 73;
scores[2] = 33;
# instantiatino syntax
bool truthtable[3] = {false, true, true}
bool truthtable[] = {false, true, true}
// size is optional in instantiatino syntax
- In C, if you pass an array as input to a function, you have to also pass another argument of how big the array is as well
float average(int length, int array[])
String
- String is an array of chars
string s = "HI!";
printf("%c %c %c", s[0], s[1], s[2]);
- use
string.h
NUL
- the last byte of a string will always be 0, a special delimiting character NUL
string s = "HI!";
printf("%i %i %i %i\n", s[0], s[1], s[2], s[3]); // 72 73 33 0
- the variable indicate where the string begins, the 0 indicate where the string ends
- The double quotes imply that it’s a string & it needs to be terminated with backslash 0
int main(void)
{
string s = get_string("Input: ");
printf("Output: ");
// inititalize strlen here too!!
for (int i = 0, n = strlen(s); i < n; i++)
{
printf("%c", s[i]);
}
print("\n");
}
Multi-dimension
- Arrays can consist of more than a single dimension
- You can have as many size specifiers as you wish
bool battleship[10][10]
- 10 x 10 grid of cells
- In memory though, it’s just a 100-element 1D array
- Multi-dimensional arrays are great abstractions to help visualize gameboards or other complex representations
- We can’t treat entire arrays themselves as variables
- we CANNOT assign one array to another using the assignment operator (not legal C)
- we must use a loop to copy over the elements one at a time