In this program, the average of several integers is computed via an array. That is, a number of integers whose average is supposed to be computed are assigned to an array and an integer pointer is used to access the array elements. A function named findaverage is defined, to which the integer pointer and the count of the numbers are passed. In the function, an assert is used that ensures that the pointer is not NULL. If the pointer is not NULL, the array elements are accessed through the pointer and their addition is done. After the addition of the numbers, their average is computed. The computed average is then returned to the main function where the average is displayed on the screen. If the pointer is not pointing to the array and is instead pointing to NULL, the program will display an error and will be aborted.
The program is compiled using GCC, as shown in the following screenshot. Because no error appears during compilation, this means the assertprog.c program is successfully compiled into a .exe file: assertprog.exe. Because the pointer is pointing to the array while executing the file, we get the average of the numerical values specified in the array, as shown in the following screenshot:
Next, comment out the following line in which the pointer is pointing to the array:
ptr=arr;
The ptr pointer now is pointing to NULL. Hence, on running the program, it will display an error, as shown in the following screenshot:
Voilà! We have successfully used assertions to ensure that our pointer is not pointing to NULL.
Now, let's move on to the next recipe!