-
Notifications
You must be signed in to change notification settings - Fork 0
tutorial arrays
Ever get tired of writing variable1, variable2, variable3, ... variable100
?
Arrays in C have fixed length. This means that once you declare them, you can't change their size.
Arrays are declared more or less like variables; after the name, add brackets with the desired length of the array.
int array[10]; // declare an array with 10 elements
Arrays can also be declared as type*
; if the array is assigned at creation, this will be automatically given the appropriate length.
int *array = {1, 2, 3, 4, 5};
NOTE: just declaring the array, and not assigning values creates something called a pointer that is discussed later.
Access arrays using the bracket operator:
int array[10];
array[5] = 42; // Set the 5th element to 42
int x = array[5]; // Retrieve the 5th element
printf("%d\n", x);
Since C wasn't designed by degenerates, Arrays are indexed starting at 0; therefore, a 10 element array has indices 0,1,2...9 available:
int array[10];
array[0] = 1; // ok
array[9] = 1; // all good
array[10] = 1; // *refuses to compile*
On a related note, C doesn't have strings. Instead, we have char*
: arrays of characters.
char *thisIsAString = "This is a string.";
printf("%s\n", thisIsAString);