Arrays
In C an array is a variable that can store multiple values of the same data type. When declaring it you must define how many values the array can hold. You can then access particular elements by using indexes which start at 0. In C array out of bounds, meaning the index is not in the range of , can not be checked by the compiler and therefore does not throw an error. An out of bounds exception can cause the program to crash or unexpected behavior. Arrays are initialized with the default value of that type but you can also specify specific values when initializing.
#include <stdio.h>
void printIntArray(int arr[], int length){
printf("%d", arr[0]);
for(int i = 1; i < length; i++) {
printf(", %d", arr[i]);
}
printf("\n");
}
int main()
{
int empty[1];
int marks[5] = {19, 10, 8, 17, 9};
int otherMarks[] = {1,2,3}; // length is inferred
int moreMarks[5] = {[2]=10, [4]=40}; // all others are 0
printIntArray(empty, 1);
printIntArray(marks, 5);
printIntArray(otherMarks, 3);
printIntArray(moreMarks, 5);
return 0;
}
-410826608
19, 10, 8, 17, 9
1, 2, 3
0, 0, 10, 0, 40
Multidimensional arrays
In C you can also create multidimensional arrays so which are arrays of arrays. Just as in other language 2D can be visualized as a table. You can also go further like 3D etc. but this can quickly get very confusing.
Pointer arithmetic
Interestingly the name of an array is also a pointer to the first element of an array which we can make use of with a concept called pointer arithmetic to iterate through the array.
#include <stdio.h>
void printIntArray(int* arr, int length) {
int *arr_end = arr + length;
for(int* ptr = arr; ptr < arr_end; ptr++){
printf("%p\t%d\n", (void*)ptr, *ptr);
}
}
int main()
{
int marks[] = {19, 10, 8, 17, 9};
int* ptr = marks; // same as &marks[0]
printIntArray(ptr, 5);
return 0;
}