/* A demo of arrays and some of the
fiddly details
Marc Chee (cs1511@cse.unsw.edu.au), March 2021
*/
#include <stdio.h>
void print_array(int array[], int length);
int main(void) {
// Different ways of initialising an array
// ---------------------------------------
// 1. All zeroes
int array_1[10] = {};
// 2. The exact numbers given {exactly the same number of elements}
int array_2[10] = {1,2,3,4,5,6,7,8,9,10};
// 3. The numbers, then zeroes. Anything not specified after the
// {given numbers} is made into zero
int array_3[10] = {1,2,3};
// 4. Not initialised . . . can't be used
int array_4[10];
print_array(array_1, 10);
print_array(array_2, 10);
print_array(array_3, 10);
// Careful! Using uninitialised memory is very dangerous
// We have no idea what it will be
//print_array(array_4, 10);
// Some array usage demos
// ----------------------
// declare an array, all zeroes
int student_marks[10] = {};
// make first element 85
student_marks[0] = 85;
// access using a variable
int access_index = 3;
student_marks[access_index] = 50;
// copy one element over another
student_marks[2] = student_marks[6];
// cause an error by trying to access out of bounds
student_marks[10] = 99;
}
// A function for printing an array of integers
// Assumes that length is <= the size of the array
// and will print the first length elements on a
// line separated by spaces
void print_array(int array[], int length) {
int i = 0;
while (i < length) {
printf("%d ", array[i]);
i++;
}
printf("\n");
}
Resource created Tuesday 02 March 2021, 05:35:38 PM.
file: arrays_demo.c